javascript - 查找动态生成的 li 元素

标签 javascript jquery html css

我正在尝试获得一些 <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/

相关文章:

javascript - 客户关系管理 2015 : Custom Ribbon buttons in quote entity not visible after the quote is activated

JavaScript Promises : chaining promises with non-promise objects. 为什么有效?

Javascript 错误隐藏在 ASP.NET 应用程序中

html - 无法在文本区域中输入文本 - HTML

html - 为什么 hr 和 img 标签周围有空白?

javascript - 为什么 jQuery 幻灯片在选择时弹跳?

javascript - Anime js onclick 为选择器添加动画

javascript - 当字符串包含 src =""或 id =""属性时,不能 $.parseJSON()

javascript - 格式化 Javascript 输出

javascript - 如何防止加载查询的 css 应用于整个页面?