gpt4 book ai didi

javascript - 有没有办法知道元素是在表还是列表中?

转载 作者:行者123 更新时间:2023-12-02 18:30:15 25 4
gpt4 key购买 nike

我正在制作一个通用删除函数,它将删除一条记录,然后删除 <tr>如果该元素位于 <table> 内,或 <li>如果它在 <ul>

该元素可以位于表格内的列表中,因此我需要知道哪个父元素最接近。

有没有办法使用 jQuery 找出这个?

最佳答案

如果我理解正确的话,你想要这样的东西:

if ($(this).closest('li').length) {
$(this).closest('li').remove();
} else { // must be in a table
$(this).closest('tr').remove();
};

http://api.jquery.com/closest

万一您的元素位于 li 内的表格中,您需要更具创意:

if ($(this).closest('li').length) {
if ( $(this).closest('li').is($(this).closest('tr').closest('li')) ) {
// then we're in a table inside an li
$(this).closest('tr').remove();
} else {
$(this).closest('li').remove();
};
} else { // must be in a table
$(this).closest('tr').remove();
};

http://api.jquery.com/is

关于javascript - 有没有办法知道元素是在表还是列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17865830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com