【问题标题】:How can I get values of inputs that have the same class using JQuery each?如何使用 JQuery 获取具有相同类的输入值?
【发布时间】:2012-10-17 18:49:11
【问题描述】:

这应该很容易,但我似乎无法做到。

var totalHours = 0;
this.$(".timesheet-daily-input").each( function () {
    var inputValue = $(this).text();
    var hours = parseInt(inputValue);
    totalHours += (hours == null) ? 0 : hours;
});

我也尝试过$(this).val()$(this).html(),但无法从输入字段中获取值。

编辑:抱歉,我知道我忘了提一些事情。 “这个”。在每个循环的开始是因为我正在使用主干的模型和集合。第一个“这个”。指有问题的具体型号。它循环了正确的次数,我就是无法获得值。

【问题讨论】:

  • 那个这个的作用是什么?
  • this.$(".timesheet-daily-input"). 是不是搞错了?
  • 去掉$前的“this”。如果这是窗户,也许它可以工作,但它不干净。并使用 val() 获取值。
  • 您的问题是什么?什么不工作?
  • 它循环了适当的次数,但没有得到任何值。如果我将alert(inputValue) 放在var inputValue 行之后,则警告框不包含任何内容。

标签: jquery html class backbone.js selector


【解决方案1】:

去掉$(".timesheet-daily-input")之前的this.,使用$(this).val()获取输入的值。

【讨论】:

  • “这个”。一开始是指我正在使用的特定模型。我没有提到我正在使用主干的模型和集合。如果我不包括“这个”。一开始,它会遍历我的所有输入,而不是特定模型的输入。
【解决方案2】:
var inputValue = $(this).val();

【讨论】:

    【解决方案3】:

    没有更多代码很难说,但要改变

    var inputValue = $(this).text();
    var hours = parseInt(inputValue);
    totalHours += (hours == null) ? 0 : hours;
    

    var inputValue = $(this).val(); // use val
    var hours = parseInt(inputValue, 10); // use 10 as radix
    totalHours += isNaN(hours) ? 0 : hours; // compare to NaN instead of null
    

    注意parseInt("09") is 0和parseInt的结果不能是null

    【讨论】:

      【解决方案4】:

      找不到确切的解决方案,但通过选择父 div 并循环遍历它的子元素来改变我的方法。

      var totalHours = 0;
      this.$("#timesheet-daily-entry-fields-container").children().each(function () {
          var inputValue = $(this).val();
          var hours = parseInt(inputValue);
          totalHours += isNaN(hours) ? 0 : hours;
      });
      

      【讨论】:

        猜你喜欢
        • 2023-01-12
        • 2021-05-11
        • 1970-01-01
        • 2016-09-10
        • 2015-02-17
        • 2012-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多