访问刚刚附加到 DOM 的 jquery 元素 [英] Getting access to a jquery element that was just appended to the DOM

查看:26
本文介绍了访问刚刚附加到 DOM 的 jquery 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 DOM 上添加一个元素,例如:

I am simply appending an element that is on the DOM like:

$("#div_element").append('<a href="#">test</a>');

在我追加它之后,我需要访问我刚刚创建的元素以便将点击功能绑定到它,我尝试了:

Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:

$("#div_element").append('<a href="#">test</a>').click(function(){alert("test")});

但是上面的方法没有用.我可以对元素进行唯一标识,但这似乎有点太多工作,因为也许有一种方法可以在我追加元素后立即获取该元素.

But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.

推荐答案

您可以这样做:

var el = $('<a href="#">test</a>');

$("#div_element").append(el);

el.click(function(){alert("test")});

// or preferrably:
el.on('click', function(){alert("test")});

append 函数接受两种类型的参数:字符串或 jQuery 元素.如果传入一个字符串,它将在内部创建一个 jQuery 元素并将其附加到父元素.

The append function accepts two types of arguments: a string or a jQuery element. In case a string is passed in, it will create a jQuery element internally and append it to the parent element.

在这种情况下,您希望自己访问 jQuery 元素,因此您可以附加事件处理程序.因此,与其传入字符串并让 jQuery 创建一个元素,不如先创建该元素,然后再将其传递给 append 函数.

In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.

完成此操作后,您仍然可以访问 jQuery 元素以附加处理程序.

After you've done that, you still have access to the jQuery element to be able to attach the handler.

这篇关于访问刚刚附加到 DOM 的 jquery 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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