event.stopPropagation() 在 Firefox 浏览器中无法正常工作,但在 Google Chrome 或 Internet Explorer 或 Opera 中工作正常,Firefox 浏览器中的问题是单击 btn_1 时应显示消息 btn_1 而不是显示 div1 .还有其他功能或者解决这个问题的方法吗?非常感谢
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>Hello!</title>
<style type="text/css">
<!-- body {
text-align: center;
}
#main {
position: absolute;
height: 400px;
width: 600px;
border: 1px solid black;
left: 400px;
}
#btn1 {
position: absolute;
height: 30px;
width: 200px;
border: 1px solid black;
left: 500px;
top: 420px;
}
#btn2 {
position: absolute;
height: 30px;
width: 200px;
border: 1px solid black;
left: 800px;
top: 420px;
}
#div1 {
height: 100px;
width: 100%;
background-color: #FF3399;
}
#div2 {
height: 100px;
width: 100%;
background-color: #99FF00;
position:relative;
}
#div3 {
height: 100px;
width: 100%;
background-color: #00CC99;
}
-->
</style>
<script>
function addElement2() {
var element = document.getElementById("main");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var newContent = 0;
for (var i = 0; i <= 2; i++) {
newContent = newContent + 1;
var divname = "div" + newContent;
var divname2 = "div" + newContent;
var Content_text = "newContent" + newContent;
divname = document.createElement("div");
document.getElementById("main").appendChild(divname);
Content_text = document.createTextNode(divname2);
divname.id = divname2.toString().trim();
divname.appendChild(Content_text);
var btn = document.createElement("BUTTON")
document.getElementById(divname2.toString().trim()).appendChild(btn);
var btn_id= "btn_" + newContent;
btn.id =btn_id;
var Content_text2 = document.createTextNode("btn_" + newContent);
btn.appendChild(Content_text2);
btn.onclick = function(){delete_cooke1(this) ;} ;
divname.onclick = function(){go_to(this) ;} ;
}
}
function delete_cooke1(mmm){
event.stopPropagation();
var str = mmm.id.toString() ;
alert(str);
return;
}
function go_to(mmm){
var str = mmm.id.toString() ;
alert(str);
return;
}
</script>
</head>
<body>
<div id="main"></div>
<button id="btn1" onclick="addElement2()">1-Create 3 divs</button>
</body>
</html>
最佳答案
您需要将事件
对象显式传递到回调函数中。例如:
document.querySelector("body").onclick = function(e){
console.log(e); // the current event
};
您正在利用 Chrome 将当前事件公开为全局 on the window 的事实(即 window.event
或只是 event
)。 Firefox 不会这样做——并且other browsers也会受到影响。
关于javascript - event.stopPropagation() 在 firefox javascript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063515/