![](/img/trans.png)
[英]jquery/javascript finding the value within a dynamically created element id
[英]Finding value of checkbox in dynamically created element
因此,我正在编写一些JS,它可以动态创建一些DOM元素。 下面是创建的元素的结构:
<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);
});
我的代码undefined
得到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>
你只是想念'。' 在类选择器之前
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
console.log(x);
});
我发现您的选择器有误。 类点丢失。 试试这个:
$('.cont[key="' + $(this).attr('key') + '"')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.