我正在尝试获得一些 <li>
以这种方式从 javascript 函数动态生成的元素:
function readPicture(file){
if (file) {
var reader = new FileReader();
var randomNumberText = Math.random().toString(36).substring(7);
reader.onload = function (e) {
$('.past').append('<li><img data-whatever="'+e.target.result+'" id="picture'+randomNumberText+'"/></li>');
};
reader.readAsDataURL(file);
}
}
在点击事件中,我试图以这种方式获取那些 li 元素:
$('#body').on('click','#upload',function(){
$('.past').find('li').each(function(){
console.log('ok');
});
});
HTML
<button id="upload">ok</button>
<div class="photo_attach">
<ul class="past"></ul>
</div>
li 元素是自动生成的,这是问题的根源。所以任何人都可以给我一些选择
最佳答案
我猜问题出在下一行,因为其他代码看起来没问题:
$('#body').on('click','#upload',function(){
应该是:
$('body').on('click','#upload',function(){
从正文选择器中删除 #
它将起作用。
$('.past').append('<li>First item</li><li>Second item</li><li>Third item</li>');
$(function(){
$('body').on('click', '#upload',function(){
$('.past').find('li').each(function(){
console.log('ok');
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="upload">ok</button>
<div class="photo_attach">
<ul class="past">
</ul>
</div>
关于javascript - 查找动态生成的 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34509298/