将我的事件处理程序绑定到哪个事件

Which event to bind my event handler to?

本文关键字:事件 绑定 我的 事件处理 程序      更新时间:2023-09-26

在我的HTML中,我有一个如下的表骨架:

<table>
    <thead id="table-headings"></thead>
    <tbody id="table-body"></tbody>
</table>

此外,我有一个<div id="content"></div>,稍后将使用。

我使用$.ajax()请求以动态方式用行和列填充表体。表中的每个单元格都填充了一个<a href="#">some link here</a>。单击其中一个链接,就完成了对服务器的另一个$.ajax()请求,并且应该将更多数据放入div#content中。由于链接是动态加载的,所以我使用这样的事件委派:

$('#table-body').on('click', 'a', function(event) {
    $.ajax({
        // some settings here
        success: function(response) {
            // Append some data to the content div
            $('#content').append(...);
        }
    });    
});

所有这些都很好。现在,问题来了:我附加到div#content的一些数据是由<pre></pre>标记包围的html源代码。我想使用代码片段jQuery语法突出显示插件来突出显示此源代码。根据事件授权规则,这在理论上应该通过做来工作:

$('#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
            $('#content').append(...);
            $('#content').find('pre').snippet('html');
        }
    });    
});

您不需要任何事件。。。只需在ajax成功函数中使用find获取<pre>标签在附加内容之后。。这边DOM元素将已经添加到文档中。。并且能够找到

success:function(response){
  ....//your stuff;
  $('#content').find('pre').snippet('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);
        }
    });    
});