jQuery-检查DOM元素是否已经存在 [英] jQuery - Check if DOM element already exists

查看:127
本文介绍了jQuery-检查DOM元素是否已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过Ajax和jQuery动态添加一些表单元素. 我要确保不会两次创建相同的元素,所以我只想在尚未将其添加到DOM的情况下添加它.

I am trying to add some form elements dynamically via Ajax with jQuery. I want to make sure that I don't create the same element twice, so I only want to add it if it hasn't already been added to the DOM.

我所有的元素都有唯一的CSS ID,例如:

All of my elements have a unique CSS id, for example:

$('#data_1')

我正在使用以下方法检查该元素是否已经存在:

I am using the following to check if the element already exists:

if ($('some_element').length == 0) {
    //Add it to the dom
}

但是,它仅适用于首次加载时已属于页面的元素.

However, it only works for elements which were already part of the page when it first loaded.

我还如何检查页面加载后动态创建的元素?

How do I also check for elements which were dynamically created after the page was loaded?

任何建议都值得赞赏.

谢谢.

推荐答案

这应适用于所有元素,而不管它们何时生成.

This should work for all elements regardless of when they are generated.

if($('some_element').length == 0) {
}

在ajax回调函数中编写代码,它应该可以正常工作.

write your code in the ajax callback functions and it should work fine.

这篇关于jQuery-检查DOM元素是否已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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