标签云点击事件多次触发:函数重复执行问题排查求助
Hey there, let's break down why your tag clicks are firing multiple functions (like popping up 3,2,1 or 2,1 instead of just one alert). I looked through your code and found two main culprits:
1. Broken HTML tag closing (the core issue)
Take a look at your tag divs—you're closing each one with </a> instead of the correct </div>:
<div id="firstword" class="weight-1" onclick="func1()">Cloud1</a> <div id="secondword" class="weight-2" onclick="func2()">Cloud2</a> <div id="thirdword" class="weight-3" onclick="func3()">Cloud3</a>
When browsers encounter invalid HTML like this, they automatically try to fix the DOM structure. In this case, it ends up nesting your divs inside each other (so thirdword becomes a child of secondword, which becomes a child of firstword).
Thanks to event bubbling, when you click the innermost tag, the click event travels up to all its parent elements. That means all the click handlers on those parent divs get triggered too—hence the sequence of alerts you're seeing.
2. Duplicate event bindings (a secondary issue)
You're using two different ways to attach click events to your tags:
- Inline
onclickattributes in the HTML (likeonclick="func1()") - jQuery's
.click()method in your script (like$("#firstword").click(function() { alert("first."); });)
Even if you fixed the HTML nesting, this would cause double alerts if you uncommented your func1()/func2()/func3() functions.
How to fix this
Step 1: Fix the HTML tag closing
Replace all those incorrect </a> tags with </div>:
<div class="cloud"> <div id="firstword" class="weight-1">Cloud1</div> <div id="secondword" class="weight-2">Cloud2</div> <div id="thirdword" class="weight-3">Cloud3</div> </div>
Step 2: Pick one event binding method
Stick to either inline handlers OR jQuery bindings—don't use both.
Option A: Keep jQuery bindings
Remove the inline onclick attributes from your HTML, and keep your jQuery code (note I also removed the extra semicolons):
$(function() { $("#firstword").click(function() { alert("first."); }); $("#secondword").click(function(){ alert("second."); }); $("#thirdword").click(function(){ alert("third."); }); });
Option B: Use native JS inline handlers
Remove the jQuery binding code, uncomment your function definitions, and keep the inline onclick attributes:
function func1(){ alert("1"); }; function func2(){ alert("2"); }; function func3(){ alert("3"); };
Step 3: Clean up unused code
That <foo class="bar"> block doesn't serve any purpose and could mess with DOM parsing—go ahead and delete it:
<!-- Remove this entire section --> <div> <foo class="bar"> <foo id="ba"></foo> </foo> </div>
After making these changes, each tag click will only trigger its corresponding alert once.
内容的提问来源于stack exchange,提问作者user3093444

