2013-03-11 24 views
1

我是js的新手,只学了一周左右,所以请友好。下面的脚本改变了iframe的src,以便在单击.thumb类的链接时匹配同一iframe的自定义数据属性。JQuery - 将变量的值传递给类的索引值

这工作正常,但它目前正在改变所有iframe的所有类的iframe src与.gallery的父级div类。我只是想用与'clicked'变量相同的索引值来更改.gallery的iframe src。

//When an link with a class of .thumb is clicked 

$(document).on('click', '.thumb', function() { 

    //variable index is the index of the links parent 'li' 
    var clicked = $(this).parent('li').index(); 

    // Find iFrames of all .comm-gallery elements and alter their src to iframes data-src value 
    $('.gallery').find("iframe").prop("src", function(){ 

     // Set their src attribute to the value of data-src 
     return $(this).data("src"); 
    }); 
}); 

我已经试过在过去的几个小时无数循环的解决方案,但没有工作过,正如我不太了解这一点的JS,我想,我在这的最小公分母。任何帮助将不胜感激!返回数据-SRC之前

+0

你尝试'像'$ .eq'( '画廊')。找到( “IFRAME”)。EQ(点击).prop(..'? – 2013-03-11 17:45:18

+0

已经接受了对方的回答,但是这 – 2013-03-11 18:09:37

+0

如果'.eq'对你有用,那么我建议你就这样做,它更像是迭代1项和迭代所有项目并比较索引。 – 2013-03-11 18:22:39

回答

3

添加条件

$('.gallery').find("iframe").prop("src", function(){ 
if($(this).index() == clicked) 
    // Set their src attribute to the value of data-src 
    return $(this).data("src"); 
}); 
+0

'.eq'似乎比做内部比较要好很多,那就是如果我正确理解它的话 – 2013-03-11 17:46:38

+0

感谢您的快速响应! 。我试图实现的每个方法!谢谢谢谢谢谢!我会+1你但它不会允许我,因为我是一个noob与低代表,所以我希望“你真棒”会做! – 2013-03-11 17:51:05

0

jQuery的EQ选择是你的后:

http://api.jquery.com/eq-selector/

所以这样的:

$('.gallery').find("iframe").prop("src", function(){ 

    // Set their src attribute to the value of data-src 
    return $(this).data("src"); 
}); 

变为:

$('.gallery').find("iframe").eq(clicked).prop("src", function(){ 

    // Set their src attribute to the value of data-src 
    return $(this).data("src"); 
}); 
+0

谢谢!要花几个小时坐下来,了解这是它显然是js的一个基本组成部分。我上周学习的js在基础知识和小生境之间交错,这不是最好的方法。 – 2013-03-11 20:54:10

0

您必须选择具有'gallery'css类的元素,并且单击li的索引。

$(document).on('click', '.thumb', function() { 
var clicked = $(this).parent('li').index(); 
$('.gallery').eq(clicked).find("iframe").prop("src",function({ 
return$(this).data("src"); 
}); 
}); 
+0

谢谢!欣赏它! – 2013-03-11 20:54:38