我将动态元素添加到div标签中。之后,我想对这个新添加的元素执行click事件。但它不起作用。
以下是代码。
$(document).ready(function () {
$('#login-option').click(function () {
$.ajax({
url: "http://localhost/cgi-bin/login_form.pl",
type: "GET",
dataType: "html",
//expect html to be returned
// script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#proper-form').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);
alert("script error");
},
// error
// script call was successful
success: function (response) {
$("div#proper-form").html('<b id="testid"> testing</b>');
}
});
$('div#proper-form').fadeIn(5000);
return false;
});
$('div#proper-form').on('click', '#testid', function () {
alert("working as expected");
});
});
添加了新元素,但点击不起作用。可以帮我找到这里的错误。
任何帮助都会有很大的帮助。
由于
答案 0 :(得分:0)
尝试使用
$('#testid').bind('click', function() {
....
}
答案 1 :(得分:0)
您好请注意以下代码并进行测试
$(document).ready(function(){
$('#login-option').click(function () {
$.ajax( {
url: "http://localhost/cgi-bin/login_form.pl",
type: "GET",
dataType: "html", //expect html to be returned
// script call was *not* successful
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#proper-form').text("responseText: " + XMLHttpRequest.responseText
+ ", textStatus: " + textStatus
+ ", errorThrown: " + errorThrown);
alert ("script error");
}, // error
// script call was successful
success : function(response)
{
$("div#proper-form").html('<b id="testid"> testing</b>' );
$('#testid').bind('click', function () {
alert ("working as expected");
});
}
});
$('div#proper-form').fadeIn(5000);
return false;
});
});