如何为Meteor嵌套each元素编写鼠标移入事件并修复弹窗仅生效一次问题
Hey there, let's break down why your hover events only work for the first box and fix it step by step!
The Root Cause
You nailed the core issue: HTML IDs must be unique across the entire page. When you reuse id="jbox" in your nested each loops, the browser only binds the event to the first element with that ID. On top of that, calling $(".popup").show()/hide() targets all popup elements at once, which would cause every popup to open/close together even if you fixed the ID problem.
Step 1: Swap Repeated IDs for Classes
First, update your HTML to use classes instead of duplicate IDs. Replace id="jbox" with class="jbox" — this lets us target all job boxes instead of just the first one:
{{#each listjobName this.release this.project}} <div class="ui small menu jbox" style="background-color:{{getStatusColor buildStatus}}; padding-top: 5px; padding-right: 3px; padding-bottom: 5px; padding-left: 8px;"> <p id="viewJob"><h5>{{job}}</h5></p> <div class="ui fluid popup left transition hidden"> <div class="ui column relaxed grid"> <a class="item">Last Build: {{lastBuild}}</a> <a class="item">Last Successful Build: {{lastSuccess}}</a> <a class="item">Duration: {{lastDuration}}</a> <a class="item">Robo Results: {{robotResult}}</a> </div> </div> </div> {{/each}}
Note: You also have other repeated IDs like id="rel" in your loops — swap those for classes too to avoid similar issues down the line!
Step 2: Update Event Handlers to Target Specific Elements
Next, modify your JavaScript to use the class selector and target only the popup inside the hovered box. Use event.currentTarget to reference the exact box that triggered the hover, then find its child popup:
Template.status.events({ 'mouseenter .jbox'(event, instance) { console.log("mouse enter"); // Show only the popup inside the hovered job box $(event.currentTarget).find(".popup").show(); }, 'mouseleave .jbox'(event, instance) { console.log("mouse exit"); // Hide only the popup inside the box we're leaving $(event.currentTarget).find(".popup").hide(); }, });
Why This Works
- Using
class="jbox"ensures the event binds to every job box, not just the first. event.currentTargetpoints to the exact box the user is hovering over, so we don't affect other elements..find(".popup")targets only the popup that's a direct child of the hovered box, so each hover controls its own unique popup content.
内容的提问来源于stack exchange,提问作者Smitha S Hegade

