【问题标题】:Using the jQuery each() function to loop through classname elements使用 jQuery each() 函数循环遍历类名元素
【发布时间】:2011-07-14 14:29:57
【问题描述】:

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

我有这个..

function calculate() {

    // Fix jQuery conflicts
    jQuery.noConflict();

    jQuery(document).ready(function(){    

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



    });    

}

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

【问题讨论】:

    标签: javascript jquery each


    【解决方案1】:
    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() 函数。

    【讨论】:

    • 非常感谢!!这可能是一个愚蠢的问题,但“它的索引是什么意思”?
    • 集合中的索引。因此,例如,如果您有 3 个与选择器匹配的元素,则此变量将在每次迭代 et 时递增,它将表示当前元素的索引。
    • 一次更正,使用 Rails 和 jquery-rails (3.1.0) 的参数是第一个索引,然后是 currentElemnt:jQuery('.calculate').each(function(index,currentElement) ..
    • 我可以使用的东西:stackoverflow.com/questions/27277272/… ?
    【解决方案2】:
            $('.calculate').each(function(index, element) {
            $(this).text()
            });
    

    【讨论】:

    • 此答案与问题不一致:$('.editable') 既未在问题中声明,也未在答案中声明
    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多