2015-03-19 78 views
0

我創建與使用jQuery當場跨度一個div,像這樣綁定事件DIV

$("[data-modal]").click(function(event) { 
    event.preventDefault(); 

    var container = $("<div></div>").addClass("modal m-form").appendTo(document.body); 
    var close = $("<span></span>").addClass("modal-close").appendTo(container); 
} 

到目前爲止好...

然後,我結合一個事件來選擇模式關閉,像這樣

$(".modal-close").click(function(event) { 
    alert("close the dialog"); 
}); 

一個不工作,所以我已經試過這一個,沒有成功:

$(".modal-close").on("click", function(event) {   
    alert('close the dialog'); 
}); 

我在做什麼錯?

回答

1

你必須將其綁定到下一個靜態父。 意思是如果你有一個永遠不會被改變的父元素,將它綁定到這個上(在你的情況下可能是整個模態的包裝)。 如果您還沒有靜態包裝,您還可以將其綁定到文檔:

$(document).on('click', '.modal-close', function(event) { 
    alert("close the dialog"); 
}); 
0

要將事件綁定到動態創建的元素,您可以使用.on()。您已經使用.on()錯誤,請檢查下面的代碼 -

$(document).on("click",".modal-close", function(event) { 
    alert("close the dialog"); 
}); 

More Information for .on()