Javascript 使用 jQuery each() 函数循环遍历 classname 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5292037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:30:25  来源:igfitidea点击:

Using the jQuery each() function to loop through classname elements

javascriptjqueryeach

提问by Brett

I am trying to use jQuery to loop through a list of elements that have the same classname & extract their values.

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

I have this..

我有这个..

function calculate() {

    // Fix jQuery conflicts
    jQuery.noConflict();

    jQuery(document).ready(function(){    

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



    });    

}

I was reading up on the each() function though got confused how to use it properly in this instance.

我正在阅读 each() 函数,但对如何在这种情况下正确使用它感到困惑。

回答by Darin Dimitrov

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
});

and if you wanted to get its index in the collection:

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

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

Reference: .each()and .val()functions.

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