【问题标题】:JQuery: How to attach event to template objects?JQuery:如何将事件附加到模板对象?
【发布时间】:2011-04-12 01:42:36
【问题描述】:

我有一个生成图像的模板,我将它绑定到 div。

<script id="postTemplate" type="text/html">
<div class="post_1">
    <div class="postImage"><img src="${ImageUrl}" alt="Image"></div>
</div>
</script>

然后我绑定数据

<script>
    $("#postTemplate").tmpl(clientData).appendTo("#imagesArea");
</script>

现在,我想要为我刚刚创建的添加一个事件处理程序。像

("template img").error(function() {});

为 click 之类的东西添加处理程序似乎可以工作,但是在我添加处理程序之前会触发错误。

【问题讨论】:

    标签: jquery templates


    【解决方案1】:

    不确定您的选择器“模板 img”引用的是什么,因为我没有看到任何模板元素。

    $(function(){
    
        $('template img').live({
          click: function() {
            // do something on click
          },
          error: function() {
            // do something on error
          }
        });
    });
    

    http://api.jquery.com/live/

    【讨论】:

    【解决方案2】:
    $("template").on("error", "img", function(){});
    

    【讨论】:

      【解决方案3】:

      怎么样

      $("#postTemplate img").click(function() { alert('clicked'); });
      

      必须在添加模板后调用。否则你将不得不使用 Live

      【讨论】:

        【解决方案4】:

        我不确定我是否遇到了您的问题,但我想您可以先从模板中存储对生成对象的引用,然后再将其附加到 #imagesArea 元素,将事件附加到该引用应该如下:

        var myGeneratedContent = $("#postTemplate").tmpl(clientData)
        myGeneratedContent.appendTo('#imagesArea');
        myGeneratedContent.click(function() { [...] });
        

        【讨论】:

          【解决方案5】:

          试试

          ("template img").bind("error",function() {});
          

          【讨论】:

            【解决方案6】:

            你可以使用 .live(),即使元素是之后创建的,它也会绑定事件

            $("#imagesArea img").live('click', function(){
               //do stuff here
            });
            

            【讨论】:

            • 您不必使用 live() ... 在元素被创建/附加到 DOM 之后,有很多方法可以将事件附加到元素上。 .live() 很方便。
            • 你说得对,我知道......对不起,我没有选择正确的词......我刚刚编辑了我的帖子,谢谢
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-01-31
            • 1970-01-01
            • 2011-09-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-03-14
            相关资源
            最近更新 更多