【问题标题】:jquery delegate problem with jquery templatesjquery模板的jquery委托问题
【发布时间】:2010-07-13 21:38:18
【问题描述】:

我一直在使用 jQuery 模板代码(github 上的 jquery.tmpl.js),它对我来说效果很好。但是,我正在尝试使用委托将事件附加到内容,但它不起作用。这是插入模板后的简化 HTML 结构:

<!-- static in the html file -->
<div id="container">
  <!-- this div is inserted multiple times by the jquery template code -->
  <div class="rule">
    <button>Save</button>
  </div>
</div>

在我的 Javascript 中我已经设置好了

$(".rule").live("click", function() {console.log("live click");});

$("#container").delegate("click", ".rule button", function() {
  console.log("delegate click");
});

当页面运行时,我可以点击模板插入的按钮,但我只能在 Firebug 的控制台日志中收到“实时点击”消息。委托事件永远不会触发。我已经为委托尝试了几个不同的目标/上下文,虽然我认为我上面的内容是正确的,但我无法让它工作。

有人有什么建议、指点或我可以尝试的事情吗?

谢谢! 道格

【问题讨论】:

    标签: jquery templates delegates


    【解决方案1】:

    delegate() 的正确语法是 delegate( selector, eventType, handler )

    使用

    $("#container").delegate(".rule button", "click", function() {console.log("delegate click");});
    

    【讨论】:

    • &lt;button&gt; 没有class="rule",它在 &lt;div class="rule"&gt;
    • 感谢您的“拍脑袋”,把事情弄清楚了。我发誓我已经看过委托的文档,上面写着“委托(事件类型,选择器,处理程序)”,但是您的建议效果很好。我认为除了格式不正确的委托调用之外,我的部分问题是我一直在使用的上下文选择器。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2013-06-18
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多