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

标签 javascript jquery

我正在制作一个通用删除函数,它将删除一条记录,然后删除 <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/

相关文章:

javascript - Jquery添加多个div

php - 如何从 php/mysql 加载 DojoX 日历的事件?

javascript - jQuery ajax 表单提交 - 如何确保使用动态加载的表单操作

javascript - 加载网站时随时清除浏览器缓存

javascript - 单选按钮组包含复选框组

javascript - 如何处理表格: &lt;input&gt; and <select> in Cordova/Phonegap

javascript - 将动态值分配给剑道网格列模板中的全局变量

javascript - 如何强制 .prepend() 和 .append() 添加 DOM 对象,而不是文本

javascript - THREE.js 使正交相机适合场景

javascript - 改变css使黑色