我有一个mainbox
,其中动态生成了更多盒子。
// first time retrive
$.post("dataretrive.php", {
}, function(data, status) {
document.getElementById('mainbox').innerHTML = data;
timer();
});
然后单击这些子框,我正在实现一些功能
$('.boxes-main').unbind('click').on('click', '.subbox', function(e){
var value1 = $(this).attr('data');
var value2 = $(this).attr('data2');
var value3 = $(this).attr('data3');
var value11 = $(this).attr('data4');
var value12 = $(this).attr('data5');
var value13 = $(this).attr('data6');
...... // some more functionality with these data which i think doesn't matter for this question for this question
});
因为我想实现这些子框
的快捷方式,例如当用户按 1 时,它会触发该框上的单击事件。我也有与之相关的 ID。如 box1 、 box2 、 box3 等。我试图在按下键 1 时放置该框的单击事件。
$(document).keypress(function(e) {
if(e.charCode == 49) {
$('#box1').click();
}
});
我还尝试了 trigger
函数,$("boxes-main #box1').click();
但没有任何效果,因为内容是动态生成的。有人告诉请问如何在动态生成的元素上实现手动单击事件。
不要混淆 boxes-main
和 mainbox
两者都是同一 div 元素的类和 id。
最佳答案
根据您的评论:
and don't get confused between boxes-main and mainbox both are class and id of same div element.
并不是点击生成被破坏,而是您在委托(delegate)的 click
事件处理程序中定位了错误的祖先。向更高的祖先前进,到达一个不变的元素。如果没有其他更接近的话,document
是最好的默认值。
$(document).on('click', '.subbox', function(e){
注释:
- 不要将
bind
与on
混合使用。使用off
代替 - 在此示例中,您根本不需要
off
/unbind
关于javascript - 如何在动态生成的元素上实现手动单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35317248/