将单击事件附加到尚未添加到 DOM 的 JQuery 对象 [英] Attaching click event to a JQuery object not yet added to the DOM

查看:21
本文介绍了将单击事件附加到尚未添加到 DOM 的 JQuery 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将点击事件添加到 JQuery 对象之前,我在将其添加到 DOM 之前遇到了很多麻烦.

I've been having a lot of trouble attaching the click event to a JQuery object before adding it to the DOM.

基本上我有这个按钮让我的函数返回,然后我将它附加到 DOM.我想要的是用自己的点击处理程序返回按钮.我不想从 DOM 中选择它来附加处理程序.

Basically I have this button that my function returns, then I append it to the DOM. What I want is to return the button with its own click handler. I don't want to select it from the DOM to attach the handler.

我的代码是这样的:

createMyButton = function(data) {

  var button = $('<div id="my-button"></div>')
    .css({
       'display' : 'inline',
       'padding' : '0px 2px 2px 0px',
       'cursor' : 'pointer'
     }).append($('<a>').attr({
       //'href' : Share.serializeJson(data),
       'target' : '_blank',
       'rel' : 'nofollow'
     }).append($('<image src="css/images/Facebook-icon.png">').css({
       "padding-top" : "0px",
       "margin-top" : "0px",
       "margin-bottom" : "0px"
     })));

     button.click(function () {
        console.log("asdfasdf");
     });

     return button;     
}

返回的按钮无法捕捉到点击事件.但是,如果我这样做(在按钮添加到 DOM 之后):

The button that is return is unable to catch the click event. However, if I do this (after the button is added to the DOM):

$('#my-button').click(function () {
    console.log("yeahhhh!!! but this doesn't work for me :(");
});

它有效...但不适合我,不是我想要的.

It works... but not for me, not what I want.

这似乎与对象还不是 DOM 的一部分有关.

It seems to be related to the fact that the object is not yet a part of the DOM.

哦!顺便说一句,我正在使用 OpenLayers,我将按钮附加到的 DOM 对象是一个 OpenLayers.FramedCloud (它还不是 DOM 的一部分,但一旦触发了几个事件,它将是.)

Oh! By the way, I'm working with OpenLayers, and the DOM object that I'm appending the button to is an OpenLayers.FramedCloud (Which is not yet a part of the DOM but will be once a couple of events are triggered.)

推荐答案

使用这个.您可以将 body 替换为 dom 就绪上存在的任何父元素

Use this. You can replace body with any parent element that exists on dom ready

$('body').on('click', '#my-button', function () {
     console.log("yeahhhh!!! but this doesn't work for me :(");
});

查看此处http://api.jquery.com/on/ 了解更多信息从 1.7+ 开始,使用 on() 代替 live().

Look here http://api.jquery.com/on/ for more info on how to use on() as it replaces live() as of 1.7+.

下面列出了您应该使用的版本

Below lists which version you should be using

$(选择器).live(事件、数据、处理程序);//jQuery 1.3+

$(selector).live(events, data, handler); // jQuery 1.3+

$(document).delegate(selector, events, data, handler);//jQuery 1.4.3+

$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+

$(document).on(事件、选择器、数据、处理程序);//jQuery 1.7+

$(document).on(events, selector, data, handler); // jQuery 1.7+

这篇关于将单击事件附加到尚未添加到 DOM 的 JQuery 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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