给定一个父元素,测试某些子元素

发布于 2024-08-13 14:37:35 字数 391 浏览 4 评论 0原文

我有以下代码:

<table id="myTable">
    <th>Date</th>
    <th>Action</th>
</table>

并且

var $table = $('#myTable');

我的 JS 中有一个条件,我将在该表中附加表行 (),但我想编写一个函数来检查是否任何已添加或未添加。

因此,我正在寻找一个布尔表达式,如果 $table 包含任何 标签,则返回 true,否则返回 false。初步答案让我相信我需要使用 jQuery ':has' 选择器。

I have the following code:

<table id="myTable">
    <th>Date</th>
    <th>Action</th>
</table>

and

var $table = $('#myTable');

There is a condition in my JS where I will be appending table rows (<tr>) to this table, but I want to write a function to check to see if any have been added or not.

So I'm looking for a boolean expression that returns true if $table contains any <tr> tags, and false otherwise. Preliminary answers lead me to believe I need to use the jQuery ':has' selector.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

撩起发的微风 2024-08-20 14:37:35

您可以使用 :has() 选择器。您可以在括号内使用任何选择器。例如,:has(tr) 检查元素是否包含任何 tr 元素。

You can use the :has() selector. You can use any selector inside the parenthesis. For example, :has(tr) checks whether the element contains any tr elements.

吾性傲以野 2024-08-20 14:37:35

if (jQuery('table').find('tr').size() > 0) {
  // has element
}


if (jQuery('table').find('tr').size() > 0) {
  // has element
}

征﹌骨岁月お 2024-08-20 14:37:35

你可以做类似的事情:

jQuery("table").find("certainTr").size > 1

使用:has选择器

我不是100%我当然明白你的问题...如果我不在的话请告诉我

You could do something like :

jQuery("table").find("certainTr").size > 1

or use the :has selector

I'm not 100% sure I understood your question... let me know if I'm off

追风人 2024-08-20 14:37:35
if ($('#myTable tr').length) {
//got some tr
}
if ($('#myTable tr').length) {
//got some tr
}
弥繁 2024-08-20 14:37:35

如果您想要做的只是在表包含任何行时返回 true,如果表不包含行则返回 false,那么您可以尝试此操作...

return ($("#myTable tr").length > 0);

如果您打算有一个标题行,尽管该标题行位于表中每次您可能都想将上面脚本中的 0 更改为 1。

If all you're trying to do is return true if your table contains any rows and false if your table contains no rows then you can try this...

return ($("#myTable tr").length > 0);

If you're going to have a header row though that is in the table at all times you might want to change the 0 to 1 in the above script.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文