javascript - 如何将 jQuery 中的事件处理程序添加到 jQuery 本身之后呈现的代码中

标签 javascript jquery jquery-select2

编辑:问题已经解决,事实证明,Select2 库有一个针对此类型的自定义命令:

$("#element").on("change", function (e) { ... }
// Defined as "change"

我正在使用名为 Select2 3.2 的下拉菜单库。简而言之,该代码采用一堆选择和选项标签,并生成一个很酷的下拉搜索列表。

但是,在网站呈现之后;当我单击“查看源代码”时,我所有的选择和选项标签仍然存在,但是当我右键单击新生成的菜单本身并选择“检查元素”(使用谷歌浏览器)时,html 完全不同。

我认为这是导致问题的原因,所有这些新代码都是从自定义库的 JS 渲染的,并且是在我的 jQuery 事件命令之后。

具体来说,这是我的命令:

$(document.body).on('click', '.select2-result-label', function() {
        var name = $(this).text();
        var post_to = '/myurl/';
        $.post(post_to, { dat: dat},
            function(response) {
                ...
            }, 'json'
        )

我相信 on() 方法可以处理这种事情,但显然不是,任何帮助将不胜感激!

相关编辑: 以下是另一篇 Stack Overflow 帖子的简介:

The view page source page shows you the exact text that 
was returned by the server.     

Inspect element actually shows you the fully rendered DOM tree.

知道这一点,也许解决这个问题会更容易。

这是一个 JS Fiddle 相关的:

http://jsfiddle.net/JpvDt/47/

尝试在单击多栏中的“x”时显示警报“已生效”。 现在我的代码可以注册包含 x 的类。

$(document.body).on("click", ".select2-search-choice-close", alert("worked"));

最佳答案

场景 1:

您的问题可能是您为整个 DOM 绑定(bind)了方法,这确实很糟糕。因此,请始终尝试将其绑定(bind)到控件所在的最近的 div(最近的父元素)。

关于 Jquery API 的事件性能如下所示。

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

场景 2:

像下面这样调用您的 on 事件(带有 off 事件)。

$(#yourElement).off('click').on('click', '.select2-result-label', function() {
        var name = $(this).text();
        var post_to = '/myurl/';
        $.post(post_to, { dat: dat},
            function(response) {
                ...
            }, 'json'
        )

希望这对您有帮助。

关于javascript - 如何将 jQuery 中的事件处理程序添加到 jQuery 本身之后呈现的代码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14101062/

相关文章:

jquery - $ ('body' ).css ('overflow-y' , 'auto' ) 在 Internet Explorer 上不工作

JQuery if() 与 :contains

javascript - select2 MULTIPLE 占位符不起作用

javascript - 无法使用 select2 读取 jQuery 验证中未定义的 nodeName 属性

javascript - 如何清空select2之前的数据?

javascript - 为什么我不能用 jquery 移动我的代码

javascript - 将 JSON 反序列化为 JAVASCRIPT 对象

javascript - 如何在没有后端的情况下实现html输入表单

javascript - $.param 序列化对象到 JSON

javascript - 什么是用于选择特定 div 中具有特定类的 anchor 元素的 jQuery 选择器