jQuery for循环没有运行功能

时间:2014-10-06 20:33:36

标签: javascript jquery html for-loop

我试图在jQuery中创建一个循环,找到所有' img'元素并在其下方放置一个标题,根据元素的标题'属性。每当我运行下面的循环时,我在任何图像下都没有标题。

for (var i = 0; i < $('.myimage').length; i++) {
    $('.myimage')[i].after('<h6>' + $('.myimage').attr('caption') + '</h6>');
};

但是,当我运行此代码时

$('.myimage').after('<h6>TEST</h6>');

单词&#39; TEST&#39;出现在所有图像下方。因此,我知道我的HTML是正确的,我没有拼写错误,选择器正在工作,我只是无法让for循环工作......我做错了什么?

2 个答案:

答案 0 :(得分:4)

$('.myimage')[i]返回一个DOM元素(不是jQuery对象),因此没有after方法。如果您想循环,只需使用.each

$(".myimage").each(function() {
    //this refers to each image
    $(this).after('<h6>' + $(this).attr('caption') + '</h6>');
});

答案 1 :(得分:1)

您可以使用.myimage的回调函数循环浏览.after()这样的元素

$('.myimage').after(function(){
    return '<h6>' + $(this).attr('caption') + '</h6>';
});

一个小注,不要构成自己的属性。请改用自定义数据属性,例如data-caption="something"

<强> jsFiddle example