$ .on(“click”,function()|不单击。元素是动态生成的[重复]

问题描述 投票:-6回答:1

我有一个功能,可以生成需要的点击支票。没问题,这就是生成的html代码的样子。

<span class="edit">
   <i class="fa fa-pencil" aria-hidden="true"></i>
</span>

然后我尝试创建另一个函数,以便我可以操纵另一个div。问题是按钮似乎没有点击。这是函数的样子:

$(".edit").on('click', function(){
    //function to edit tasks
        alert("The check was clicked.");
    });

警报未显示。什么想法可能是错的?

javascript jquery html click
1个回答
1
投票

使用事件委托:

$(document).on('click', '.edit', function(){
    //function to edit tasks
    alert("The check was clicked.");
});

var c = $('#c');
$('#add').on('click', function(){

c.append('<span class="edit"><i class="fa fa-pencil" aria-hidden="true"></i> Hello</span>');

});

$(document).on('click', '.edit', function(){
        //function to edit tasks
        alert("The check was clicked.");
});
div {
   margin-top:10px;
}
.edit {
   width:25px;
   height:25px;
   margin: 0px 10px 10px 0px;
   background:#000;
   color:#fff;
   padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<button id="add">Add</button>
<div id="c"></div>
© www.soinside.com 2019 - 2024. All rights reserved.