Javascript 要将我的事件处理程序绑定到哪个事件?
在我的HTML中,我有一个如下的表骨架:Javascript 要将我的事件处理程序绑定到哪个事件?,javascript,jquery,event-handling,Javascript,Jquery,Event Handling,在我的HTML中,我有一个如下的表骨架: <table> <thead id="table-headings"></thead> <tbody id="table-body"></tbody> </table> 所有这些都很好。现在,问题来了:我附加到div#content的一些数据是被 $('#content').on('...', 'pre', function(event) { $(this)
<table>
<thead id="table-headings"></thead>
<tbody id="table-body"></tbody>
</table>
所有这些都很好。现在,问题来了:我附加到div#content
的一些数据是被
$('#content').on('...', 'pre', function(event) {
$(this).snippet('html');
});
我的问题是,我不知道应该将事件处理程序绑定到哪个JavaScript事件。基本上,我只想在加载代码片段后突出显示它们,但似乎没有适合这里的JavaScript事件,因为jQuery的load()
和ready()
方法用于不同的目的。如何突出显示动态加载的html代码 您是否尝试过:
$('#table-body').on('click', 'a', function(event) {
$.ajax({
// some settings here
success: function(response) {
// Append some data to the content div
$newElemement=$(response)
$('pre',$newElement).snippet('html')
$('#content').append($newElement);
}
});
});
你为什么不试试:
success:function(response){
....//your stuff;
$('#content').find('pre').snippet('html');
}
你不需要为这个做任何事情。。。只需使用find获得Awesome,这很好用。:)但是,我假设将行$('#content').find('pre').snippet('html')整个方法块中的代码>也起作用。但它只在$.ajax()调用的成功处理程序中起作用。你能告诉我为什么吗?它也可以,但在我看来更具可读性:)我想你也可以写$('content')。('pre')。代码片段('html'),但我正在工作,无法正确地测试它。哦,你是对的。我又犯了一个错误。无论如何,非常感谢,您的解决方案非常有效。:)在成功处理程序中,当调用find()时,内容已经附加到DOM中,因此可以找到它。如果你把它放在外面,它就不起作用了,因为ajax是异步的,追加操作很可能发生在find('pre')之后。确切地说,我现在也想到了这一点。感谢您的澄清。:)我也谢谢你。:)但是@lek0更快,所以我会接受这个解决方案+不过我还是要给你一个建议。很高兴知道find()
也适用于动态加载的选择器。
$('#table-body').on('click', 'a', function(event) {
$.ajax({
// some settings here
success: function(response) {
// Append some data to the content div
$newElemement=$(response)
$('pre',$newElement).snippet('html')
$('#content').append($newElement);
}
});
});
success:function(response){
....//your stuff;
$('#content').find('pre').snippet('html');
}