繁体   English   中英

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

[英]Which event to bind my event handler to?

在我的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源代码。 我想使用snippet 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');
        }
    });    
});

你不需要任何事件...只需在内容被追加后使用find在ajax成功函数中获取<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);
        }
    });    
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM