我正在尝试将一个变量连接到 JQuery 选择器中(我认为这相当简单),但我遇到了一些有趣的行为。我的代码应该取消选中 y 轴上的某些单选选择器。
for(var i = 1; i < 5; i++) {
$("input[value='"+1+"']").each(function() { //<--
$(this).on('change', function() {
var that = this;
$("input[value='"+1+"']").each(function() { //<--
if($(this).attr('name') != $(that).attr('name')) {
$(this).prop('checked', false);
}
});
});
});
}
现在,代码按原样运行(即仅选择值“1”的输入),并且也可以使用引号中包含的“1”。但是,一旦我传入 i
或 i.toString()
,代码就不起作用。理想情况下,我希望能够传入 i
来激活我的所有输入
。这可能吗?我正在使用 http://code.jquery.com/jquery-1.10.2.min.js
中的 JQuery。
HTML
<form method="POST" action="votes.php">
<div style="border:black solid 1px;border-radius:5px;">
<label>One</label>
<input type="radio" name="one" value="1">
<input type="radio" name="one" value="2">
<input type="radio" name="one" value="3">
<input type="radio" name="one" value="4">
</div>
<div style="border:black solid 1px;border-radius:5px;">
<label>Two</label>
<input type="radio" name="two" value="1">
<input type="radio" name="two" value="2">
<input type="radio" name="two" value="3">
<input type="radio" name="two" value="4">
</div>
<div style="border:black solid 1px;border-radius:5px;">
<label>Three</label>
<input type="radio" name="three" value="1">
<input type="radio" name="three" value="2">
<input type="radio" name="three" value="3">
<input type="radio" name="three" value="4">
</div>
<div style="border:black solid 1px;border-radius:5px;">
<label>Four</label>
<input type="radio" name="four" value="1">
<input type="radio" name="four" value="2">
<input type="radio" name="four" value="3">
<input type="radio" name="four" value="4">
</div>
</form>
最佳答案
这是 JavaScript 中经典的闭包问题。在您的代码中,将 1
替换为 i
(第二个 i
,位于事件处理程序中)将不起作用,因为这些事件处理程序维护实际的链接到 i
变量本身,而不是代码运行时 i
所保存的值
解决方案很简单:通过将 i
作为参数传递给函数来打破闭包:
for(var i = 1; i < 5; i++) {
(function(i){
$("input[value='"+ i +"']").each(function() {
$(this).on('change', function() {
var that = this;
$("input[value='"+i+"']").each(function() { //<--
if($(this).attr('name') != $(that).attr('name')) {
$(this).prop('checked', false);
}
});
});
});
})(i);
}
关于jquery - 在 JQuery 选择器中连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20897915/