【问题标题】:Find number value assigned to checkbox from jquery从jquery中查找分配给复选框的数字值
【发布时间】:2014-06-06 09:27:39
【问题描述】:

我有一个 ASP.NET MVC 剃须刀页面,它有一个循环,循环中有一个 CheckboxFor。我为每个复选框分配了一个数字值。我还分配了一个类,以便当这些复选框值中的任何一个发生更改时,我可以在 jquery 中捕获 onchange 事件:

@Html.CheckBoxFor(modelItem => item.PrincipleInvestigator, new { Value = item.ProjectResearcherId, @class = "Principle-investigator-checkbox" })

然后,在 jquery 中,我想要被点击的特定复选框的数值:

$(".Principle-investigator-checkbox").change(function () {
    alert($(".Principle-investigator-checkbox").val);
});

这是行不通的。我实际上不知道如何确定单击了列表中的哪个复选框。 this.val 之类的东西?另外,我不确定.val 是否给了我分配给它的数值,但是如果我检查呈现的 HTML,可以看到该值:

<input value="4570" class="Principle-investigator-checkbox" data-val="true" data-val-required="The PrincipleInvestigator field is required." id="item_PrincipleInvestigator" name="item.PrincipleInvestigator" type="checkbox">

【问题讨论】:

  • 这是$(".Principle-investigator-checkbox").val() 而不是$(".Principle-investigator-checkbox").val
  • 另外,处理click 事件而不是change。它更适合checkboxes
  • 此外,在事件处理程序中,您可以通过$(this) 引用元素。您不需要重复选择器,它将引用接收事件的元素,而不是第一个(如果您有多个共享相同的class)。
  • 开始理解 jQuery 的好方法是阅读以下内容:api.jquery.com

标签: jquery asp.net asp.net-mvc razor checkbox


【解决方案1】:
$(".Principle-investigator-checkbox").change(function () {
    alert(this.value);
    //or  alert($(this).val());
    //avoid alert($(".Principle-investigator-checkbox").val());
});

this.value

这里this指的是原生DOM元素,所以我们可以参考原生DOM属性value来获取值

$(this).val()

这里我们用 jQuery 对象包装原生 DOM 元素。因此,我们需要使用 jQuery 包装器对象上的方法来获取值。那是 val()方法

避免警报($(".Principle-investigator-checkbox").val())

val() 是一个 getter 方法,它总是会返回第一个匹配的元素,而不是所有元素。在处理多元素选择器时,最好在更改函数中使用this

【讨论】:

  • +1。值得一提的是,如果您在事件处理程序中再次使用选择器,它将返回列表中的第一个元素(返回多个时)。
  • 它的类选择器它将返回我认为的所有值
  • @EhsanSajjad,不。检查提供的文档链接Get the current value of the first element in the set of matched elements or set the value of every matched element。你可以自己试试
【解决方案2】:

$(".Principle-investigator-checkbox") 将选中该类的所有复选框,因为有多个 checbkxes,您必须编写 $(this) 以使用单击的一个引用获取当前单击的一个值,如下所示:

$(".Principle-investigator-checkbox").change(function () {
    alert($(this).val()); //gets value of current checkbox which caused event
});

另外val 不是一个函数,它是val()

【讨论】:

    【解决方案3】:

    val 是方法而不是属性 使用val() 而不是val

    $(".Principle-investigator-checkbox").change(function () {
        alert($(this).val());
    });
    

    还在事件处理程序中使用$(this)。否则,它将采用 .Principle-investigator-checkbox 类的第一个元素的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 2018-08-08
      • 2012-12-05
      相关资源
      最近更新 更多