【问题标题】:jQuery add ID to parent table then remove TDjQuery将ID添加到父表然后删除TD
【发布时间】:2011-12-15 22:16:54
【问题描述】:

我有一个 TD,其中嵌套了一个图像,我想向它的父级添加一个 ID,然后删除该 TD。以下代码将根据嵌套在其中的图像删除 TD,但在删除之前,我想在它的父表中添加一个 ID。有什么建议吗?

$('td img[src="/v/vspfiles/templates/cyberfront/images/RBox_Border_Left_Top.gif"]').parent().remove();

【问题讨论】:

  • 添加id,然后删除...有什么问题?
  • 想将ID添加到父表中。

标签: jquery html-table add


【解决方案1】:

使用closestendclosest 找到与选择器匹配的最近的祖先元素,end 返回上一个选择。

所以...

$('td img[src="/v/vspfiles/templates/cyberfront/images/RBox_Border_Left_Top.gif"]')
    .parent() // go to the td
        .closest('table') // go to the table
            .prop('id', 'foobar') // set the table's id property
        .end() // go back to the td
        .remove(); // remove it

【讨论】:

  • 我认为.end() 是我最喜欢的新功能,直到今天我才知道。为分享您的答案而欢呼。
  • 我不知道为什么这不起作用...它甚至损坏了页面上的其他 JavaScript。
  • 你有什么版本的jQuery?如果它是旧的(1.6 之前的)升级它或将prop 更改为attr。这是它无法正常工作的最可能原因。
【解决方案2】:
$('td img[src="/v/vspfiles/templates/cyberfront/images/RBox_Border_Left_Top.gif"]').parent().closest("table").attr('id','newId');

$('td img[src="/v/vspfiles/templates/cyberfront/images/RBox_Border_Left_Top.gif"]').parent().remove();

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 2020-12-14
    • 1970-01-01
    • 2013-10-10
    • 2017-01-16
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多