问题是当我在动态添加的div中按下该按钮时,没有任何反应。事件根本不触发。
我试图在HTML中添加该div,然后重试,该事件工作。所以我想这是因为div被动态添加。
添加的div有一个mainTaskWrapper类,该按钮有一个类checkButton。
事件在下面的script.js文件的末尾使用.on()附加。
这是我的代码:
helper_main_task.js :(这是添加div的对象,你不必阅读它,因为我认为这是关于该动态添加的div,但是如果你需要的话)
var MainUtil = { tasksArr : [],catArr : ["all"],add : function(){ var MTLabel = $("#mainTaskInput").val(),//task label MTCategory = $("#mainCatInput").val(),//task category MTPriority = $("#prioritySlider").slider("value"),//task priority MTContents = $('<div class="wholeTask">\ <div class="mainTaskWrapper clearfix">\ <div class="mainMarker"></div>\ <label class="mainTaskLabel"></label>\ <div class="holder"></div>\ <div class="subTrigger"></div>\ <div class="checkButton"></div>\ <div class="optTrigger"></div>\ <div class="addSubButton"></div>\ <div class="mainOptions">\ <ul>\ <li id="mainInfo">Details</li>\ <li id="mainEdit">Edit</li>\ <li id="mainDelete">Delete</li>\ </ul>\ </div>\ </div>\ </div>'); this.tasksArr.push(MTLabel); //setting label MTContents.find(".mainTaskLabel").text(MTLabel); //setting category if(MTCategory == ""){ MTCategory = "uncategorized"; } MTContents.attr('data-cat',MTCategory); if(this.catArr.indexOf(MTCategory) == -1){ this.catArr.push(MTCategory); $("#categories ul").append("<li>" + MTCategory +"</li>"); } $("#mainCatInput").autocomplete("option","source",this.catArr); //setting priority marker color if(MTPriority == 2){ MTContents.find(".mainMarker").css("background-color","red"); } else if(MTPriority == 1){ MTContents.find(".mainMarker").css("background-color","black"); } else if(MTPriority == 0){ MTContents.find(".mainMarker").css("background-color","blue"); } MTContents.hide(); $("#tasksWrapper").prepend(MTContents); MTContents.slideDown(100); $("#tasksWrapper").sortable({ axis: "y",scroll: "true",scrollSpeed : 10,scrollSensitivity: 10,handle: $(".holder") }); } };
$(function(){ $("#addMain,#mainCatInput").on('click keypress',function(evt){ if(evt.type == "click" || evt.type =="keypress"){ if((evt.type =="click" && evt.target.id == "addMain") || (evt.which == 13 && evt.target.id=="mainCatInput")){ MainUtil.add(); } } }); //Here's the event i'm talking about : $("div.mainTaskWrapper").on('click','.checkButton',function(){ alert("test text"); }); });
解决方法
从documentation(是的,其实是大胆的):
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
. To ensure the elements are present and can be selected,perform event binding inside a document ready handler for elements that are in the HTML markup on the page.[…]
By picking an element that is guaranteed to be present at the time the delegated event handler is attached,you can use delegated events to avoid the need to frequently attach and remove event handlers.
您可能需要将其绑定到#tasksWrapper:
$("#tasksWrapper").on('click',function(){ alert("test text"); });