2012-10-10 81 views
0

我不觸發每次一個jQuery事件:jQuery的事件不總是觸發

http://jsfiddle.net/LphjL/

我的代碼:

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被觸發,但是:

如果您點擊'Homepage',然後點擊'Generic infos'並重新更新輸入字段沒有觸發Ajax:$(".websiteElement").change事件不是第二次調用。

回答

1

您需要使用事件委託綁定事件,或者在替換元素後重新綁定事件。以下是事件委託選項:

$("#panel-content").on("change",".websiteElement",function() { 
    updateDatabase($(this).attr('id'), $(this).val()); 
}); 

如果事件直接綁定在元素上,則當元素被替換/刪除時,事件將會丟失。