带有jquery属性的动态按钮

好吧,我可以生成一个包含表单代码的按钮

var temp = ""; $('#myDiv').append(temp).click(function(){ window.alert("Hello! My id is " + this.id); }); 

然后在运行时这并没有真正起作用,因为我得到了id作为“myDiv”的答案。 另一方面,我也尝试使用这样的东西:

 $('#myDiv').append(temp).click(dynButtonClicked(this)); 

其中dynButtonClicked分别定义为

 function dynButtonClicked (aButton) { window.alert("Hey, my id is " + aButton.id); }; 

但是,通过这种方式,在页面加载时点击按钮,id为’undefined’,而且,无论我点击按钮多少次,我都没有得到进一步的警报(除了我在页面加载时获得的警报) )。 那么,我该怎么做呢?

我想理想情况下我想为运行时生成的所有按钮的类命名,然后点击其中的任何按钮来处理它们的某个位置。

 $(document).ready(...) 

function。 但请,请继续告诉我你的想法。 事实上,稍后,通过交互,我可能想要删除按钮或禁用它们。 所以,我正在寻找一些强大的东西。 提前感谢您的时间。

以下是如何使用jQuery方式:

 var $button = $('', { type: 'button', 'class': 'dynBtn', id: 'anID', text: 'Here!', click: function() { window.alert('Hello! My id is '+ this.id); } }); $button.appendTo('#myDiv'); 

那是因为.append()不返回附加的元素,在这种情况下你可以使用.appendTo()

 $(temp).appendTo('#myDiv').on('click', function() { window.alert("Hello! My id is " + this.id); }); 

如果要向DOM添加许多元素,最好使用事件委派。

 $('#myDiv').on('click', '.appendedElement', fn); 

使用on(),这样做:

 $(document).ready(function(){ //in here you put the event for all elements with dynBtn class $(document).on("click",".dynBtn",function(){dynButtonClicked();}); }); function dynButtonClicked (aButton) { window.alert("Hey, my id is " + aButton.id); }; //and append the button anytime you want var temp = ""; $('#myDiv').append(temp);