我让一个页面写成这样:
<div id=“listener”>
<ul id="top">
<li id="li-QD">
<input id="inV-QD" type="checkbox">
<label>
<input id="inC-QD" data-coor="3" data-level="0" data-order="0" data-parent="top" type="checkbox">
<span></span>
</label>
<label for="inV-QD">QD</label>
<ul id="ul-QD">
<li id="li-southPart">
<input id="inV-southPart" type="checkbox">
<label>
<input id="inC-southPart" data-coor="0" data-level="1" data-order="0" data-parent="QD" type="checkbox">
<span></span>
</label>
<label for="inV-southPart">southPart</label>
</li>
</ul>
</li>
</ul>
</div>
这是一个动态添加的列表。我将事件侦听器添加到顶部的“div”中,这样每当我单击一个输入时,我就会通过使用“even.target”来找出谁被单击了,从而获得目标名称。
现在,因为我使用的是“span”,所以当我单击时,会弹出两个事件。我想我将通过使用event[0],event[1
来告诉两个事件],但事实证明该事件是一个对象。(event是eventlistener绑定函数的参数function(event) )。我不能把它当作数组。
function bodyIni(){
let httpRequest;
httpRequest = new XMLHttpRequest();
const url = "http://localhost/mapMonitor/areaIni.php";
httpRequest.onreadystatechange = alertContents;
httpRequest.open("GET",url,true);
httpRequest.send();
function alertContents(){
if(httpRequest.readyState === XMLHttpRequest.DONE){
if(httpRequest.status ===200){
//alert(httpRequest.responseText);Add innetHTML
document.getElementById("dym-List").innerHTML=httpRequest.responseText;
//stopPropagation <span> $$ <label[for]>
const spans = document.querySelectorAll("#listener span")
for(let index=0;index<spans.length; index++){
spans[index].addEventListener("click",function(e){e.stopPropagation();},false);
}
const labelFors = document.querySelectorAll("#listener label[for]")
for( index=0;index<labelFors.length; index++){
labelFors[index].addEventListener("click",function(e){e.stopPropagation();},false);
}
}
else{
alert("this is the wrong part.");
}
}
}//End of Dym-adding part
// add listener to "#dym-List"list
const list = document.getElementById("listener");
list.addEventListener("click",getElementUsingId,false);
}
我使用这个函数选中了input复选框。
function getElementUsingId(event){
let tarname = event.target;
let nameId = tarname.id;
let index = nameId.indexOf("-")+1;
//get the district Name
let name = nameId.substring(index);
//store select name.
selectName = name;
//get the name ,with prefix, we can call associate functions;
const liNameID = "#li-"+name;
uncheckAllBox();
checkAllChildBox(liNameID);
const inCName = "inC-"+name;
showArea(inCName);
//showMap(name);
}
我的方法是使用document.querySelect()
查找所有跨度,并对每个跨度使用event.stopPropagation()
。我认为这并不好。
你可以在最后一个函数中看到,如果我不停止“span”和label[for]
,我将同时得到两个事件。event.target
会给出两个输出,也就是两个对象,而不是在一个数组中,我能用类似数组的方式来分离两个事件吗?,.So,.So,
发布于 2018-07-14 03:56:25
如果您只想处理跨度上的事件,则可以执行以下操作:
if (event.target.tagName == "SPAN") {
event.stopPropagation();
// rest of event processing
}
https://stackoverflow.com/questions/51331489
复制相似问题