如何将加载处理程序附加到动态创建的项目 [英] How to attach load handler to dynamically created items

查看:157
本文介绍了如何将加载处理程序附加到动态创建的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个加载处理程序绑定到一个动态创建的对象(我的生产代码中的骨干视图)。我试图使用中概述的方法在jQuery中,如何将事件附加到动态HTML元素?,它适用于点击处理程序,但不适用于加载处理程序。有没有人知道如何解决这个问题?

I am trying to bind a load handler to a dynamically created object (backbone view in my production code). I tried to use the approach outlined in In jQuery, how to attach events to dynamic html elements?, and it works for a click handler but not a load handler. Does anyone know how to solve this?

这个工作(与点击处理程序)

This works (with click handler)

  $(document).ready(function() {
    $("body").on("click", "img", function(){
      console.log("foo");
    });

    create();
  });

  function create(){
    $img = $("<img />").attr("src", "http://www.pureweber.com/wp-content/uploads/2011/04/jquery_icon.png");
    $("body").append($img);
  }

但这不(与加载处理程序)

But this doesn't (with load handler)

  $(document).ready(function() {
    $("body").on("load", "img", function(){
      console.log("foo");
    });

    create();
  });

  function create(){
    $img = $("<img />").attr("src", "http://www.pureweber.com/wp-content/uploads/2011/04/jquery_icon.png");
    $("body").append($img);
  }


推荐答案

不幸的是,具有子选择器的上的c $ c>仅适用于冒泡的事件类型。 DOM 加载事件不会引发树,所以它永远不会到达您正在收听的正文

Unfortunately the usage of on with a subselector only works with event types that bubble up. The DOM load event does not bubble up the tree, so it will never reach body where you are listening for it.

请参阅 http://en.wikipedia.org / wiki / DOM_events

您将需要手动将处理程序附加到您创建的任何图像。

You will need to manually attach the handler to any images you create.

$(document).ready(function() {
  $("body img").on("load" onLoad);

  create();
});

functon onLoad(){
    console.log("foo");
}

function create(){
  $("<img />")
    .on('load', onLoad)
    .attr("src", "http://www.pureweber.com/wp-content/uploads/2011/04/jquery_icon.png")
    .appendTo('body');
}

这篇关于如何将加载处理程序附加到动态创建的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆