我的结构类似
getDerivedStateFromProps
当我点击任何div时,它会调用第一个函数。如何实现只有我点击div然后调用相应函数的情况。我是javascript的新手。
答案 0 :(得分:5)
由于您的DIV彼此嵌套,因此click事件将冒泡到每个元素。如果您只希望它在您单击的内部DIV上,则需要调用event.stopPropagation()
来停止冒泡。这意味着您必须将event
对象传递给函数。
<div onclick="first(event)">
//first div
<div onclick="second(event)">
//second div
<div onclick="third(event)">
//my content here inner div
</div>
</div>
</div>
然后功能必须像:
function first(e) {
e.stopPropagation();
// rest of code here
}
答案 1 :(得分:1)
您可以使用event.stopPropagation()
来阻止click
事件冒泡。
function first(){
this.event.stopPropagation();
alert( 'first div' );
}
function second(){
this.event.stopPropagation();
alert( 'second div' );
}
function third(){
this.event.stopPropagation();
alert( 'third div' );
}
<div onclick="first()">
//first div
<div onclick="second()">
//second div
<div onclick="third()">
//my content here inner div
</div>
</div>
</div>
答案 2 :(得分:1)
尝试Event.stopPropagation()
,以防止当前事件在捕获和冒泡阶段进一步传播。
function first(e){
e.stopPropagation();
alert('first function')
}
function second(e){
e.stopPropagation();
alert('second function')
}
function third(e){
e.stopPropagation();
alert('third function')
}
&#13;
<div onclick="first(event)">
first div
<div onclick="second(event)">
second div
<div onclick="third(event)">
my content here inner div
</div>
</div>
</div>
&#13;
答案 3 :(得分:0)
问题是单击一个子div,它会触发这个div的每个父节点(点击第三个将触发第二个将首先触发)。为了防止传播,你需要stopPropagation
这样
See onclick documentation
function first(e){
e.stopPropagation();
console.log('you are in first')
}
function second(e){
e.stopPropagation();
console.log('you are in second')
}
function third(e){
e.stopPropagation();
console.log('you are in third')
}
&#13;
<div onclick="first(event)">
//first div
<div onclick="second(event)">
//second div
<div onclick="third(event)">
//my content here inner div
</div>
</div>
</div>
&#13;