[英]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.对于以下为什么不起作用,我有点难过。
The HTML is dynamically created, resulting in something like this: HTML 是动态创建的,结果如下:
<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. jQuery/Javascript 来处理用户点击行。 When they do, I'd like to trigger a click on the corresponding child div.当他们这样做时,我想触发对相应子 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).除了triggerHandler()
调用(我认为)之外,一切正常。
I'd appreciate any pointers.我会很感激任何指示。
You can use trigger()
and stop the event propagation using stopPropagation()
.您可以使用trigger()
并使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.