jQuery“each”方法

时间:2013-01-09 21:42:55

标签: jquery loops each

我是一个javascript初学者,我在使用jQuery的“each”方法时遇到了一些麻烦。我在Joomla网站上有一个库模块,可用作简单的图像滑块。我添加了一些代码以允许链接图像上的灯箱。我现在要做的是将缩略图标题(模块当前添加的标题)复制到链接中的标题属性,以便它显示在每个图像的灯箱中。

以下是HTML的结构......

<div class="camera_wrap" id="camera_wrap_106">
<div class="cameraContents">
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
</div>

我到目前为止已经获得了代码,但它只将第一个字幕div复制到每个title属性,而不是在每个实例上执行它。不确定这是否是最好的开始...

$("#camera_wrap_106 .cameraContent").each(function() {
    $("#camera_wrap_106 a.camera_link").attr('title', $("#camera_wrap_106 .camera_caption div").html());
});

提前致谢!

2 个答案:

答案 0 :(得分:3)

您可以使用attr()

的回调功能
$("#camera_wrap_106 .cameraContent a.camera_link").attr('title',function(){
    return $.trim($(this).next().text());
});

http://jsfiddle.net/nSj8h/

或者,如果您想使用每个语句,只需在选择器中设置context

$("#camera_wrap_106 .cameraContent").each(function() {
    $("a.camera_link",this).attr('title', $(".camera_caption div",this).text());
});

在选择器中添加上下文与使用find

相同
$('element',context) == $(context).find('element')

http://jsfiddle.net/baLmn/

答案 1 :(得分:2)

您应该使用this

$("#camera_wrap_106 .cameraContent").each(function() {
    $(this).attr('title', $(this).html());
});

.each提供迭代中的元素作为函数的上下文(即this)。

它也作为第二个参数提供(第一个是索引),这意味着你也可以这样写:

$("#camera_wrap_106 .cameraContent").each(function(index, element) {
    $(element).attr('title', $(element).html());
});