我动态创建了一个div并附加到div上。我正在尝试从查询中添加数据并将其加载到该文本字段。但是,我无法选择动态创建的元素,因为它已经在DOM中不可见了。这就是我的小提琴
<div id="parent">
<input id='childButton' type="button" value="Add"/>
<div id="child" data-row="0">
<input type="text" value="" />
</div>
</div>
var rowNum = 0;
$('#parent').on('click', '#childButton', function() {
var clone = $('#child').clone().attr('data-row', ++rowNum);
$('#parent').append(clone);
console.log($('#child[data-row=1]').length);
});
问题是id选择器,将仅返回具有给定id的第一个元素。在您的情况下,您将使用id子项创建多个元素。因此#child
将返回第一个child
元素,但随后应用data-row
规则将筛选出所选元素,以便获得0
结果。
解决方案是使用类而不是id来选择元素
var rowNum = 0;
$('#parent').on('click', '#childButton', function() {
var clone = $('#child').clone().attr('data-row', ++rowNum).removeAttr('id');
$('#parent').append(clone);
//here clone refers to the dynamically create element
//but if you want to fetch the element using a selector then
snippet.log($('.child[data-row=1]').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div id="parent">
<input id='childButton' type="button" value="Add" />
<div id="child" class="child" data-row="0">
<input type="text" value="" />
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句