简体   繁体   中英

How to stop event propagation in jQuery click function inside click function?

I'm having troubles stopping click event propagation. I have a click function inside another click function.

Here's what I'm trying to achieve:

  1. Select a label by clicking it
  2. Then click inside the box to determine which label was clicked

This works fine if you select labels one by one. But if you click on Label 1 and then Label 2, both events are recorded (see console log). Or if you click on Label 1 five times and then click inside the box, all five events are captured.

How can I stop this event propagation?

JSFiddle: https://jsfiddle.net/q930bvff

 var objectName, currentObject; $('.label').click(function(event) { $('.label').removeClass('selected'); $(this).addClass('selected'); objectName = $(this).attr('id'); currentObject = $(this).hasClass('selected'); if (currentObject) { $('#box').one('click', function(e) { console.log(objectName); }); } event.stopPropagation(); }); 
 html, body { font-family: 'Helvetica', Arial, sans-serif; font-size: 1em; } .label { padding: 12px; border-radius: 4px; background: #000; color: #fff; display: inline-block; cursor: pointer; } .label.selected { background: green; } #box { height: 300px; width: 300px; border: 1px solid rgba(0, 0, 0, 0.3); border-radius: 4px; margin-top: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="label-1" class="label">Label 1</div> <div id="label-2" class="label">Label 2</div> <div id="box"></div> 

Use $('#box').off("click") before every new .one("click" to kill all the previously created click handlers on #box .

See working snippet below:

 var objectName, currentObject; $('.label').click(function(event) { $('.label').removeClass('selected'); $(this).addClass('selected'); objectName = $(this).attr('id'); currentObject = $(this).hasClass('selected'); if (currentObject) { $('#box').off("click").one('click', function(e) { console.log(objectName); }); } event.stopPropagation(); }); 
 html, body { font-family: 'Helvetica', Arial, sans-serif; font-size: 1em; } .label { padding: 12px; border-radius: 4px; background: #000; color: #fff; display: inline-block; cursor: pointer; } .label.selected { background: green; } #box { height: 300px; width: 300px; border: 1px solid rgba(0, 0, 0, 0.3); border-radius: 4px; margin-top: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="label-1" class="label">Label 1</div> <div id="label-2" class="label">Label 2</div> <div id="box"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM