简体   繁体   中英

Triggering a click event on dynamically created ID (with ID based on parent element)

I'm a bit stumped as to why the following is not working.

Fiddle here .

The HTML is dynamically created, resulting in something like this:

<div id="manageStatuses">
   <div id="statusRowID_1" class="row">row 1
       <div id="statusRowBtn_1"></div>
   </div>
   <div id="statusRowID_2" class="row">row 2
       <div id="statusRowBtn_2"></div>
   </div>
   <div id="statusRowID_3" class="row">row 3
       <div id="statusRowBtn_3"></div>
   </div>
</div>
<!-- ... etc -->

jQuery/Javascript to handle the user clicking on the row. When they do, I'd like to trigger a click on the corresponding child div.

// user clicked on a status row
$('#manageStatuses').on("click", '[id^="statusRowID_"]', function () {
    var id = $(this).attr('id').split('_')[1];
    alert(`${id} row clicked`);
    // triggerHandler() instead of trigger() else it will recursively bubble up the DOM
    $(`#manageStatuses #statusRowBtn_${id}`).triggerHandler("click");
});

// handle dynamically triggered click on status child div.  This code is not reached.
$('#manageStatuses').on("click", '[id^="statusRowBtn_"]', function () {
    var id = $(this).attr('id').split('_')[1];
    alert(`${id} child dynamically clicked`);
    // do other things based on ID...
});

Everything works except the triggerHandler() call (I think).

I'd appreciate any pointers.

You can use trigger() and stop the event propagation using stopPropagation() .

 // user clicked on a status row $('#manageStatuses').on("click", '[id^="statusRowID_"]', function () { var id = $(this).attr('id').split('_')[1]; alert(`${id} row clicked`); // triggerHandler() instead of trigger() else it will recursively bubble up the DOM $(`#manageStatuses #statusRowBtn_${id}`).trigger("click"); }); // handle dynamically triggered click on status row. This code is not reached. $('#manageStatuses').on("click", '[id^="statusRowBtn_"]', function (e) { var id = $(this).attr('id').split('_')[1]; alert(`${id} child dynamically clicked`); e.stopPropagation(); // do other things based on ID... });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="manageStatuses"> <div id="statusRowID_1" class="row">row 1 <div id="statusRowBtn_1"></div> </div> <div id="statusRowID_2" class="row">row 2 <div id="statusRowBtn_2"></div> </div> <div id="statusRowID_3" class="row">row 3 <div id="statusRowBtn_3"></div> </div> </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