我有一个不会每次都触发的Jquery事件:
我的代码:
thisWebsite = websiteInitialization ();
function websiteInitialization () {
companyName = "name";
var thisWebsite = new websiteConstructor(companyName);
return thisWebsite;
}
function websiteConstructor(companyName) {
this.companyName=companyName;
}
function ajaxUpdateDB(websiteElement, value) {
return $.post('/echo/html/',{html: "<p>Text echoed back to request</p>",delay: 3}
,function(a){}
,"json"
);
}
function updateDatabase(websiteElement, value) {
var promise = ajaxUpdateDB(websiteElement, value);
promise.complete(function () {
thisWebsite[websiteElement] = value;
});
}
$(document).ready(function() {
$(".websiteElement").change(function() {
updateDatabase( $(this).attr('id'), $(this).val() );
});
$("#infos").click(function() {
htmlCode = "<input class='websiteElement' id='companyName' type='text' value='"+thisWebsite.companyName+"'>";
$("#panel-content").html(htmlCode);
});
$("#homepage").click(function() {
htmlCode = "homepage";
$("#panel-content").html(htmlCode);
});
});
正如您在jsfiddle中看到的,第一次更新输入字段时会触发Ajax,但是:
如果你点击“主页”,然后点击“通用信息”并再次更新输入字段,这一次Ajax不会被触发:第二次不会调用$(".websiteElement").change事件。
发布于 2012-10-11 01:32:16
您需要使用事件委托绑定事件,或者在替换元素后重新绑定事件。下面是事件委派选项:
$("#panel-content").on("change",".websiteElement",function() {
updateDatabase( $(this).attr('id'), $(this).val() );
});如果事件直接绑定到元素上,则当元素被替换/移除时,事件将丢失。
https://stackoverflow.com/questions/12824988
复制相似问题