Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当输入不为空时选中设置复选框_Javascript_Jquery - Fatal编程技术网

Javascript 当输入不为空时选中设置复选框

Javascript 当输入不为空时选中设置复选框,javascript,jquery,Javascript,Jquery,我有项目列表,当价格输入为空时,我需要将复选框checked值设置为true,否则设置为false <td><input type="text" value="" class="name"></td> <td><input type="text" value="" class="producer"></td> <td><input type="text" value="" class="model">

我有项目列表,当价格输入为空时,我需要将复选框checked值设置为true,否则设置为false

<td><input type="text" value="" class="name"></td>
<td><input type="text" value="" class="producer"></td>
<td><input type="text" value="" class="model"></td>
<td><input type="text" value="" class="dateOf"></td>
<td><input type="text" value="" class="color"></td>
<td><input type="text" value="" class="price"></td>
问题是,它只适用于第一个“价格”输入,如何使它适用于所有人

使用这个关键字

而不是

if (!$('.price').val())
如果类
price
有多个输入,则关键字
this
将处理您正在更改的特定输入
。price
的事件。

请重试

$('.price').keyup(function () { 
    $(this).closest('td').next().find('.checkbox').prop("checked", !$(this).val());
});

复选框在哪里?请不要告诉我ID不是唯一的,请阅读以下内容:“除了事件对象之外,事件处理函数还可以通过关键字
this
访问处理程序绑定到的DOM元素。要将DOM元素转换为可以使用jQuery方法的jQuery对象,只需执行
$(this)
”。教程很棒,它们帮助很大!你应该读一下!要稍微减少代码,您可以编写:
$(this).closest('td').next().find('.checkbox').prop('checked'),!$(this.val())
(并删除if/else语句)让我感到遗憾的是,ID并不是唯一的事实上,我已经删除了它们-\如果没有其他问题,使用类选择器仍然可以工作,不是吗?@James:
。val
将始终返回第一个选定元素的值。所以唯一的另一个“问题”是,这个类有多个元素。非常正确。没有想到多种价格。@seeinre没有问题。
if (!$(this).val()) {
if (!$('.price').val())
$('.price').keyup(function () { 
    $(this).closest('td').next().find('.checkbox').prop("checked", !$(this).val());
});