javascript - jquery动态创建元素但点击事件不起作用

标签 javascript jquery

任何 jQuery 帮助将不胜感激。我有两个用 jquery 创建的对象(相同)。一个在文档打开时加载(附加到正文标记),另一个在按钮单击事件中附加到正文标记。当我单击第一个时,它会触发一条警报消息,但第二个不会(希望它也能触发)。我已将 JSFiddle 链接包含在我的代码中。

我的代码:

<label for="" id="Label01" style="position:absolute;left:10px;top:15px;width:186px;height:23px;line-height:23px;z-index:8;">Button Created</label>

<label for="" id="Label02" style="position:absolute;left:190px;top:15px;width:186px;height:23px;line-height:23px;z-index:8;">Without Button</label> 

<label for="" id="Label03" style="position:absolute;left:30px;top:115px;width:150px;height:18px;line-height:18px;z-index:1;">Click on a image</label>

<input type="submit" id="Button1" value="Create Image" style="position:absolute;left:495px;top:100px;width:106px;height:35px;z-index:0;">

<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> 
</script>    
<script>

var $i1;
var $circle;
var dot = "dot1";
var dot_btn = "dot2";

// next (3) lines will create circle image and append to body WITHOUT button 
 click event
 $i1 =$('<i/>').attr({ class: "far fa-dot-circle fa-2x" });
 $circle = $('<div/>').attr({ id: dot 
 }).css({"position":"absolute","left":"200px","top":"40px"}).append($i1);
 $("body").append($circle);


// button click to create another circle image
$("#Button1").click(function() {             // click event - triggers a 

alert("btn clicked");
var btnCircle;

$i1 =$('<i/>').attr({ class: "far fa-dot-circle fa-2x" });
btnCircle = $('<div>').attr({ id: dot_btn 
}).css({"position":"absolute","left":"10px","top":"40px"}).append($i1);

$('#dot2').bind('click', function() { });
$("body").append(btnCircle);

});      


// NOTE only "dot1" works (without creation using the button click jquery 
  code)
$("#dot1").on("click",function() {
   alert("dot1 clicked");
});


$("#dot2").on("click",function() {
   alert("dot2 clicked");
});

</script>   

这是 jsfiddle 链接:

https://jsfiddle.net/jgwilly54/q13aLko8/1/

预先感谢您的帮助。

最佳答案

更改代码

$("#dot2").on("click",function() {
   alert("dot2 clicked");
});

$(document).on("click", "#dot2" ,function() {
   alert("dot2 clicked");
});

引用号:Event Delegation

关于javascript - jquery动态创建元素但点击事件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50779798/

相关文章:

javascript - Object.assign 没有按预期在循环中复制

javascript - Bootstrap.js 抛出选择器选项错误 : selector option must be specified when initializing tooltip on the windows. 文档对象

javascript - 使用 javascript 或 jquery 将多个广告注入(inject)页面的有效方法是什么?

javascript - 在 Javascript/jQuery 中自动化 html

jquery - 使用 jquery 构建的数据表不起作用

javascript - 如何预先计算在 waitForKeyElements() 回调中使用的内容?

javascript - 悬停时简单幻灯片放映,鼠标离开时幻灯片放映停止

JavaScript/HTML Canvas : clearing a text box

javascript - 如何正确制作 GSAP 菜单动画?

javascript - Jquery中如何获取TimeCircles Plugin的当前时间