javascript jquery 如果不存在则添加元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5059761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery add element if not present
提问by KdgDev
I'm reading a book on jQuery and it has some simple tasks and examples.
我正在阅读一本关于 jQuery 的书,它有一些简单的任务和示例。
I'm trying out the adding of an element to a table, but only if the item is not yet present.
我正在尝试将元素添加到表格中,但前提是该项目尚不存在。
The table is this:
表是这样的:
<table border="1" cellspacing="0">
<tr>
<td>Spaghetti</td>
<td>Karl</td>
</tr>
<tr>
<td>Pasta</td>
<td>David</td>
</tr>
</table>
The problem is: we're not allowed to add any classes or id's.
问题是:我们不允许添加任何类或 ID。
The idea is to add a caption. And of course, if the button is pressed 2 times, no second caption is added.
这个想法是添加一个标题。当然,如果按钮被按下 2 次,则不会添加第二个标题。
I tried this:
我试过这个:
if(!jQuery.contains('table','caption')) {
$('table').append('<caption>Orders</caption>');
}
And this
还有这个
if(!($("table:contains('caption')"))) {
$('table').append('<caption>Orders</caption>');
}
But neither work. I've read the jQuery api on the functions and selectors, I thought these would work but they don't. What do I need to do?
但两者都不起作用。我已经阅读了关于函数和选择器的 jQuery api,我认为这些会起作用,但它们没有。我需要做什么?
回答by user113716
You can get it done without the if()statement if you'd like:
if()如果你愿意,你可以在没有声明的情况下完成它:
$('table:not(:has(caption))').prepend('<caption>Orders</caption>');
This uses the not-selector(docs)and the has-selector(docs)to select <table>elements that do not have a nested <caption>element.
这使用not-selector(docs)和has-selector(docs)来选择<table>没有嵌套<caption>元素的元素。
It also uses the prepend()(docs)method to give a more expected placement in the DOM. It won't affect the actual display on the page.
它还使用prepend()(docs)方法在 DOM 中提供更预期的位置。它不会影响页面上的实际显示。
回答by Dogbert
This should work
这应该工作
if($("table caption").length === 0) {
// append caption
}
The jQuery call returns all the caption elements present inside all table elements. .lengthreturns the count of the elements. If it's 0, append the caption.
jQuery 调用返回所有表格元素中存在的所有标题元素。.length返回元素的计数。如果为 0,则附加标题。

