[英]Javascript stopPropagation
I'm just learning so probably the code is not the best. 我只是在学习,所以代码可能不是最好的。 I tried several examples in other answers but I'm stuck here.
我在其他答案中尝试了几个示例,但是我被困在这里。
Function invisibleDiv(){
var invDiv = document.createElement('div');
var secondDiv = document.createElement('div');
secondDiv.setAttribute('class', 'secondDiv');
document.body.appendChild(invDiv);
invDiv.appendChild(secondDiv);
};
And I have this jQuery code: 我有这个jQuery代码:
$(document).on("click", ".secondDiv", function (e){
e.stopPropagation();
});
All that is working but I'm trying to replace all my jQuery functions with pure Javascript so I tried this: 一切正常,但是我试图用纯Javascript替换所有jQuery函数,所以我尝试了以下方法:
document.addEventListener("DOMContentLoaded", function(event) {
var secondDiv = document.querySelector('.secondDiv').
div.addEventListener('click', function(e) {
e.stopPropagation; // Not working
secondDiv.stopPropagation; // Not working
}
});
I tried adding the event listener into the Function invisibleDiv and I can see in DevTools the event is attached, but when clicking secondDiv still triggers the event in invisibleDiv. 我尝试将事件侦听器添加到函数invisibleDiv中,并且可以在DevTools中看到该事件已附加,但是当单击secondDiv时仍会在invisibleDiv中触发该事件。
I can make it work adding both divs into the html code with Display: none/block but since it works with jQuery when added dynamically I wanna know what I'm doing wrong. 我可以使用Display:none / block将两个div添加到html代码中,但是由于动态添加时它可以与jQuery一起使用,所以我想知道自己在做错什么。
Update: 更新:
Based on your comments above, it seems to me that you're looking for something like this: 根据您上面的评论,在我看来您正在寻找这样的东西:
var outer = document.querySelector('.outer');
var inner = document.querySelector('.inner');
outer.addEventListener('click', function(e) {
console.log("Outer clicked");
});
inner.addEventListener('click', function(e) {
e.stopPropagation();
});
http://jsfiddle.net/j9a0nsto/ http://jsfiddle.net/j9a0nsto/
It looks like you're not calling the function. 好像您没有在调用该函数。
Functions in JavaScript are executed by using ()
brackets so your code becomes: JavaScript中的函数通过使用
()
括号执行,因此您的代码将变为:
e.stopPropagation();
and secondDiv.stopPropagation();
和
secondDiv.stopPropagation();
The call to secondDiv.stopPropagation()
is redundant since the element object doesn't have that function, and needs to be removed. 由于元素对象不具有该功能,因此对
secondDiv.stopPropagation()
的调用是多余的,因此需要将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.