【问题标题】:JQuery "onchange" event on just one checkbox among multiple in a group based on label text基于标签文本的组中多个复选框中的一个复选框上的 JQuery“onchange”事件
【发布时间】:2017-04-21 00:39:45
【问题描述】:

我有一组复选框 -

<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>&nbsp;

<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>&nbsp;

<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>

由于id 和name 的变量值,我无法处理带有标签One 的复选框上的onclick 事件。

我试过了,效果很好,但我不想使用check_1,因为数字 1 是可变的并且可以更改。

$("#check_1").change(function() {
  alert('Checkbox One is clicked');
});

由于我无权修改 html,我该怎么做?

【问题讨论】:

  • 使用this关键字
  • 试试$('input[type="checkbox"]')
  • $("input[id^='check_']").change()
  • @philantrovert 在这种情况下,我将如何检查下一个标签是正在检查的标签?
  • @jitendrapurohit us this 在函数内部。

标签: javascript jquery checkbox jquery-selectors


【解决方案1】:

您可以使用像 $('input[type="checkbox"]:has(+ label:contains("One"))') 这样的选择器,标签文本如下,

$('input[type="checkbox"]:has(+ label:contains("One"))').on('click', function(){
  alert('Checkbox One is clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>&nbsp;

<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>&nbsp;

<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>

【讨论】:

  • 这很好用,有没有更清洁的方法?如果我没有找到任何 +1,我会接受这个
  • 如果您想通过标签文本找到复选框,那么这是更简洁的jquery 选择器方式。如果您需要通过任何其他逻辑查找,请告诉我,我会更新答案
  • @jitendrapurohit 性能方面很好,因为这是使用单个选择器而不是使用多个选择器操作dom
【解决方案2】:

看起来您的唯一标准是 label 的文本,因此您可以根据该标签定位输入,例如:

$('label:contains("One")').prev('input:checkbox').change(function(){
    console.log('One changed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>&nbsp;

<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>&nbsp;

<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>

希望这会有所帮助。

【讨论】:

  • 我不想在两个和三个选项检查时触发警报事件
  • 你可以根据标签文本来做,检查我的更新。
  • 工作,谢谢+1。但这并不能确保点击输入是一个复选框:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2021-12-24
  • 2010-11-10
  • 2012-03-06
  • 1970-01-01
  • 2020-07-15
相关资源
最近更新 更多