我有一个这样的结构
<div onclick="first()">
//first div
<div onclick="second()">
//second div
<div onclick="third()">
//my content here inner div
</div>
</div>
</div>
当我单击任何div 时,它正在调用第一个函数。如何实现只有我点击的div然后调用相应函数的情况。我是javascript的新手。
由于您的 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
}
您可以使用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>
尝试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')
}
<div onclick="first(event)">
first div
<div onclick="second(event)">
second div
<div onclick="third(event)">
my content here inner div
</div>
</div>
</div>
问题是点击一个子div,它会触发这个div的每个父母(点击第三个将触发第二个,这将首先触发(。为了防止传播,您需要像这样stopPropagation
请参阅点击文档
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')
}
<div onclick="first(event)">
//first div
<div onclick="second(event)">
//second div
<div onclick="third(event)">
//my content here inner div
</div>
</div>
</div>