【问题标题】:Getting an error when i loop through to get input name value当我循环获取输入名称值时出现错误
【发布时间】:2022-08-16 21:18:11
【问题描述】:

无法弄清楚为什么这个循环不会给我我想要的信息

我有一个页面上有几百个输入,我想为每个检查的输入获取输入“名称”值

<input type=\"checkbox\" name=\"TAXI_SQUAD0001\" checked=\"checked\">
<input type=\"checkbox\" name=\"TAXI_SQUAD0021\" checked=\"checked\">
<input type=\"checkbox\" name=\"TAXI_SQUAD0011\">   


$.ajax({
    url: urlHPM,
    xhrFields: {
        withCredentials: true
    },
    cache: false,
    type: \"GET\",
    success: function (data) {
        checkedInputs = $(data).find(\'input[checked=\"checked\"]\'); 
        for (var i = 0; i < checkedInputs.length; i++) {
            console.log(checkedInputs.attr(\'name\')[i]); // loops character of first name of first input over and over
            console.log(checkedInputs[i].attr(\'name\')); // error attr not a function
            // i want to log input names TAXI_SQUAD0001 and TAXISQUAD0021
        }

    },
    error: function (xhr) {
    }
});
  • 试试$(checkedInputs[i]).attr(\'name\')
  • 如果你打算使用 jQuery,你应该使用 jQuery 来做循环。

标签: javascript jquery


【解决方案1】:

当您执行checkedInputs[i] 时,您正在访问 DOM。它不是 jQuery 包装的代码。你可以做checkedInputs.eq(i).attr('name') 或只是checkedInputs[i].name

您的代码也不需要 for 循环。你可以只使用每个。

checkedInputs.each(function () {
  var cb = $(this);
  console.log(cb.attr('name'));
});

【讨论】:

    【解决方案2】:

    您可以使用 .each() jQuery 函数在 ajax 成功响应中循环所有选中的复选框。

    $.ajax({
        url: urlHPM,
        xhrFields: {
            withCredentials: true
        },
        cache: false,
        type: "GET",
        success: function (data) {
            checkedInputs = $(data).find('input[checked="checked"]');
            $(checkedInputs).each(function(){
                //Log the input name attribute
                console.log($(this).attr('name'));
            });
        },
        error: function (xhr) {
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-10-02
      • 2022-01-25
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多