【问题标题】:jquery dynamic creation of element but click event not workingjquery动态创建元素但单击事件不起作用
【发布时间】:2023-03-21 21:11:01
【问题描述】:

任何 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/

提前感谢您的帮助。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    修改代码

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

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

    参考:Event Delegation

    【讨论】:

    • 可能比我的解决方案更清洁!
    • 谢谢!效果很好。
    【解决方案2】:

    我认为您最好克隆您的对象 - 这会复制整个事物,包括您想要携带的任何事件和/或数据。

    https://api.jquery.com/clone/

    刚刚在你的小提琴上做了这个,它有效。

    $("#Button1").click(function() {      
      $newObject = $( $firstObject ).clone().css( 'left', '10px' ).appendTo( 'body' );
      $( $newObject ).click( function() {
      alert( 'hey there!' );
      });
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      相关资源
      最近更新 更多