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

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

问题描述

在将Click事件添加到JQuery对象之前,我一直遇到很多麻烦。

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;     
}

返回的按钮无法捕获click事件。但是,如果我这样做(在按钮添加到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.)

推荐答案

使用此。你可以用dom上存在的任何父元素替换body

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/ 有关如何使用on()的更多信息,因为它取代了1.7+以上的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


$(选择器)。直播(事件,数据,处理程序); // 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+

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

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