所以,我正在编写一些动态创建一些 DOM 元素的 JS。下面是创建的元素的结构:
<div class='list_item' key='1'>
<p>Hello, World!</p>
</div>
<div class='cont' key='1'>
<input type='checkbox' name='test'/>
</div>
当事件被触发时,我想循环遍历所有.list_item
,并使用key
属性找到它们对应的.cont
作为标识符。我想找到 .cont > input[type="checkbox"]
的值。
这是我到目前为止的代码:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
console.log(x);
});
我的代码没有得到 true
或 false
响应,而是抛出 undefined
作为其结果。我可以对我的代码执行什么操作才能获得我想要的响应(复选框的值)?
谢谢
最佳答案
两个问题:
您忘记关闭属性选择器
您忘记了类选择器中
cont
之前的.
所以:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
// ------------^--------------------------------------^
console.log(x);
});
请注意,您可以使用单个选择器而不是 find
来完成此操作:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"] input[type="checkbox"]').prop('checked');
console.log(x);
});
示例:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"] input[type="checkbox"]').prop('checked');
console.log(x);
});
<div class='list_item' key='1'>
<p>Hello, World!</p>
</div>
<div class='cont' key='1'>
<input type='checkbox' name='test' />
</div>
<div class='list_item' key='2'>
<p>Hello, World!</p>
</div>
<div class='cont' key='2'>
<input type='checkbox' name='test' />
</div>
<div class='list_item' key='3'>
<p>Hello, World!</p>
</div>
<div class='cont' key='3'>
<input type='checkbox' name='test' checked/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 在动态创建的元素中查找复选框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409094/