我有一个div和顶部,那是另一个图像。我已经为我的div和图像提供了onClick方法。我想在点击div顶部的图像时停止为下面的div提供的onClick方法。
我能够使用e.stopPropagation();
停止它。但后来我不得不在图像的onClick上添加另一种方法。添加后,我的e.stopPropagation();
停止了工作。我该如何解决这个问题。
代码有效时
enlarge() {
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
this.setState({
showFullImage: true,
});
}
<div onClick={() => this.handleClick(content.post_poll_content_id)}>
<div className="float_right full_div" onClick={this.enlarge}>
<img src={extend} className="extend_icon" />
</div>
</div>
代码停止工作时
enlarge() {
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
this.setState({
showFullImage: true,
});
}
passImage(img){
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
this.setState({
img:img
})
}
<div onClick={() => this.handleClick(content.post_poll_content_id)}>
<div className="float_right full_div" onClick={()=>{this.enlarge();this.passImage(content.content);}}>
<img src={extend} className="extend_icon" />
</div>
</div>
答案 0 :(得分:0)
我猜你误解了stopPropagation()
。
如果要停止将代码从enlarge()
传播到passImage()
,则需要实现自定义逻辑。让我们说enlarge()
设置一个passImage()
在执行前验证的变量。
如果你真的打算停止从内部div的onClick
执行执行到外部div,它对我有效。以下是您可以测试的代码快照。
``
<html>
<head>
<script>
function click_innermostdiv1(){
event.stopPropagation();
alert("click_innermostdiv1 : innermostdiv was clicked.");
}
function click_innermostdiv2(){
event.stopPropagation();
alert("click_innermostdiv2 : innermostdiv was clicked.");
}
function click_outermostdiv(){
alert("The outermostdiv element was clicked.");
}
function click_middlediv(){
alert("The middlediv element was clicked.");
}
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;" onClick="click_outermostdiv();">
This is outermost div element.
<div style="background-color:pink" onClick="click_middlediv();">
This is middle div element. <br>
<div style="background-color:orange" onClick="click_innermostdiv1();click_innermostdiv2();">
This is a innermost div element.
</div>
</div>
</div>
</body>
</html>
``
[调试提示]当stopPropagation()
失败时,我可以想到一些可能的情况:
stopPropagation()
。