After I dynamically created three p boxes with ajax, why does it not work when I bind click events to the boxes? Is it only useful to bind events to him when ajax is created? This binds it three times. Why is this? Is there a better way?
阿神2017-07-05 11:07:56
For example, you can take a look at the jquery implementation
$("#a").click(callback);
$(document).on('click','#a',function(){ //TODO });
$("#a").live();//过时
PHP中文网2017-07-05 11:07:56
$(document).on('click','#a',function(){ //TODO }); Borrowing the answer from the first floor, I think you can find its parent element first and then bind it
仅有的幸福2017-07-05 11:07:56
I have encountered this before. Using onclick on dynamically loaded DOM does not work, because it only works on the existing DOM. Use $(document).on('click','#a',function(){} ) will work, you can try it.
phpcn_u15822017-07-05 11:07:56
You can use event delegation to achieve this, for example
<p class="wrapper">
</p>
If you want to add a list (.list) in the wrapper, you can write the delegate like this (simple writing):
//获取目标节点(这里只支持class获取)
//ele: 起始元素,最内侧的元素
//selector: className,
//stopTrget: 委托容器元素
function getTargetNode(ele,selector,stopTarget){
var clsReg = new RegExp(selector),
className = ele.className;
if(ele === stopTarget) return null;
if(clsReg.test(className)){
return ele;
} else {
return getTargetNode(ele.parentNode,selector);
}
};
//委托
function addEvent(event,ele,selector){
ele["on"+event] = function(e){
e = e || event;
var target = e.target || e.srcElement;
//当满足触发条件时
if(getTargetNode(target,selector,ele)){
//The deep♂dark♂fantasy
}
};
}
addEvent("click",document.querySelecor('.wrapper'),'.list');
过去多啦不再A梦2017-07-05 11:07:56
You can use JQ’s on method and delegate method. If it’s native, use event delegation