Javascript Jquery不适用于循环调用
我有这个界面,当我点击复选框时,输入将打开 我将JQuery用于此函数,问题是,选中复选框时,只有第一行能够打开。以下是我的代码: html:Javascript Jquery不适用于循环调用,javascript,php,html,jquery,Javascript,Php,Html,Jquery,我有这个界面,当我点击复选框时,输入将打开 我将JQuery用于此函数,问题是,选中复选框时,只有第一行能够打开。以下是我的代码: html: 名称 年龄 @foreach($people作为$people) {{$people->name} @endforeach JQuery <script> $(document).ready(function () { $('#name').on('change', function () {
名称
年龄
@foreach($people作为$people)
{{$people->name}
@endforeach
JQuery
<script>
$(document).ready(function () {
$('#name').on('change', function () {
$("#age").prop("disabled", !$(this).is(':checked'));
$("#age").val('');
});
});
</script>
$(文档).ready(函数(){
$('#name')。on('change',function(){
$(“#age”).prop(“disabled”,!$(this).is(':checked');
$(“#年龄”).val(“”);
});
});
这是因为您正在创建具有相同ID的多个HTML元素。您可以将这些ID更改为类
动态方法
您可以在复选框的父项中找到.age
输入:
使用行标识符
您还可以向包含每个输入的唯一值的输入添加一个附加属性:
@foreach($peoples as $people)
<tr>
<td >
<input type="checkbox" class="name" name="name_{{$people->id}}" person-id="{{$people->id}}"value=""/>
{{$people->name}}
</td>
<td>
<input type="number" class="age" name="age_{{$people->id}}" person-id="{{$people->id}}" value="{{$people->age}}" disabled />
</td>
</tr>
@endforeach
这似乎在循环中重复相同的ID。这是错误的方法,每次循环迭代时,您都必须更改id。同样,id必须是唯一的-
$(“#age”)
将仅引用您认为最好的第一个id,使用动态方法或行标识符方法?使用哪种方法更好,有什么具体原因吗?对于动态,您必须确保始终存在相同的结构(我想您已经有了)。有了这些ID——您只是在html代码中公开ID,但这并不是什么悲剧,两者都可以很好地使用。只是个人喜好让我们来。
@foreach($peoples as $people)
<tr>
<td>
<input type="checkbox" class="name" value=""/>
{{$people->name}}
</td>
<td>
<input type="number" class="age" value="{{$people->age}}" disabled />
</td>
</tr>
@endforeach
$(document).ready(function () {
$('.name').on('change', function () {
let input = $(this).closest('tr').find('input.age')
input.prop("disabled", !$(this).is(':checked'));
input.val('');
});
});
@foreach($peoples as $people)
<tr>
<td >
<input type="checkbox" class="name" name="name_{{$people->id}}" person-id="{{$people->id}}"value=""/>
{{$people->name}}
</td>
<td>
<input type="number" class="age" name="age_{{$people->id}}" person-id="{{$people->id}}" value="{{$people->age}}" disabled />
</td>
</tr>
@endforeach
$(document).ready(function () {
$('.name').on('change', function () {
let id = $(this).attr('person-id')
$('input.age[person-id="'+id+'"]').prop("disabled", !$(this).is(':checked'));
$('input.age[person-id="'+id+'"]').val('');
});
});