使用jQuery的each()函数遍历类名元素

26

我正在尝试使用jQuery循环遍历具有相同类名的元素列表,并提取它们的值。

我现在有这个代码...

function calculate() {

    // Fix jQuery conflicts
    jQuery.noConflict();

    jQuery(document).ready(function(){    

        // Get all items with the calculate className
        var items = jQuery('.calculate');



    });    

}

我正在阅读each()函数,但是在这个例子中如何正确使用它却感到困惑。

2个回答

78
jQuery('.calculate').each(function() {
    var currentElement = $(this);

    var value = currentElement.val(); // if it is an input/select/textarea field
    // TODO: do something with the value
});

如果您想要获取它在集合中的索引:

jQuery('.calculate').each(function(index, currentElement) {
    ...
});

参考: .each().val() 函数。


非常感谢!这可能是一个愚蠢的问题,但是“它的索引意味着什么”是什么意思? - Brett
这是集合中的索引。例如,如果您有3个与选择器匹配的元素,则此变量将在每次迭代中递增,并表示当前元素的索引。 - Darin Dimitrov
1
一个更正,使用Rails和jquery-rails(3.1.0),参数首先是索引,然后是currentElement:jQuery('.calculate').each(function(index,currentElement) .. - Albert Català
有用的东西:http://stackoverflow.com/questions/27277272/how-to-emulate-xslt-using-jquery-from-html-source? - SearchForKnowledge

3
        $('.calculate').each(function(index, element) {
        $(this).text()
        });

这个回答与问题不一致:$('.editable')在问题中没有声明,也没有在回答中声明。 - xKobalt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接