jQuery “each” method

a 夏天 提交于 2019-12-25 06:21:47

问题


I'm a javascript beginner, and I'm having some trouble using jQuery's "each" method. I have a gallery module on a Joomla site that functions as a simple image slider. I added some code to allow a lightbox on the linked images. What I would like to do now is copy the thumbnail caption (that the module currently adds) to the Title attribute in the link so it shows up in the lightbox for each image.

Here's how the HTML is structured...

<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>

I've gotten the code this far, but it only copies the first caption div to each title attribute rather than executing it on each instance. Not sure if this is even the best start...

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

Thanks in advance!


回答1:


You can use the callback function of attr()

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

http://jsfiddle.net/nSj8h/

Or if you wanted to use your each statement just set the context in your selectors

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

Adding the context in your selector is the same thing as using find

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

http://jsfiddle.net/baLmn/




回答2:


You should use this :

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

.each provides the element in the iteration as context of the function (i.e. this).

It's also provided as second argument (the first one being the index), which means you could also have written this :

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


来源:https://stackoverflow.com/questions/14247039/jquery-each-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!