好的,我可以生成一个代码为
的按钮var temp = "<button type=\"button\" class=\"dynBtn\" id=\"anID\">Here!</button>";
$('#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(...)
功能。但请,请继续告诉我你的想法。事实上,稍后,通过交互,我可能想要删除按钮或禁用它们。所以,我正在寻找一些强大的东西。提前感谢您的时间。
答案 0 :(得分:5)
以下是如何使用jQuery方式:
var $button = $('<button/>', {
type: 'button',
'class': 'dynBtn',
id: 'anID',
text: 'Here!',
click: function() {
window.alert('Hello! My id is '+ this.id);
}
});
$button.appendTo('#myDiv');
答案 1 :(得分:1)
那是因为.append()
没有返回附加的元素,在这种情况下你可以使用.appendTo()
:
$(temp).appendTo('#myDiv').on('click', function() {
window.alert("Hello! My id is " + this.id);
});
如果要向DOM添加许多元素,最好使用事件委派。
$('#myDiv').on('click', '.appendedElement', fn);
答案 2 :(得分:0)
使用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 = "<button type=\"button\" class=\"dynBtn\" id=\"anID\">Here!</button>";
$('#myDiv').append(temp);