简体   繁体   English

单击子元素时,将属性添加到元素的同级中

[英]Add an attribute to a sibling of element when the child element is clicked

I have a table with several columns, which looks like this: 我有一个table有几列,它看起来像这样:

<tr role="row" class="odd">
    <td class="sorting_1">
        <button id="1" class="btn btn-info btn-sm _edit_btn">Edit</button>
    </td>
    <td>1</td>
    <td>Asht</td>
    <td>5</td>
    <td>16</td>
    <td>5</td>
    <td>3</td>
    <td>3</td>
    <td>2</td>
    <td>Sughd</td>
    <td>2</td>
    <td>3505207000000</td>
    <td>3</td>
    <td>2</td>
    <td>15</td>
    <td>5</td>
</tr>

What I want to do is to add an attribute to each <td> element on the button click of the button which is located on the very first <td> of the table. 我想要做的是添加到每个属性<td>按钮的按一下按钮,其位于第一个元素<td>表。

I use jQuery for this purpose. 我为此使用jQuery。 I tried to do it using the siblings function but it doesn't work as the <td> elements are not siblings of the <button> element but of the other <td> elements. 我尝试使用同级函数来执行此操作,但是它不起作用,因为<td>元素不是<button>元素的兄弟姐妹,而是其他<td>元素的兄弟姐妹。

To do this you can use closest() to find the parent tr of the button , then find() to get the td , like this: 为此,您可以使用closest()查找button的父tr ,然后使用find()获取td ,如下所示:

$('button').click(function() {
    $(this).closest('tr').find('td').attr('foo', 'bar');
});

If you'd prefer to use siblings() as you mentioned, then you can get the parent td and use siblings() on that: 如果您喜欢如上所述使用siblings() ,则可以获取父td并在其上使用siblings()

$('button').click(function() {
    $(this).closest('td').siblings().attr('foo', 'bar');
});

Note that this version will not add the attribute to the first td element, if that was your intention. 请注意,如果您打算这样做,则此版本不会将属性添加到第一个td元素。

You can traverse to closest tr element using .closest() method and then find td in it: 您可以使用.closest()方法遍历到最接近的tr元素,然后在其中找到td

$('button').click(function(){
  $(this).closest('tr').find('td').attr('someattr','attrval');
});

You can use this one for two cases: 您可以在两种情况下使用此方法:

$("button").click(function(e) {
    //if you want to add attribute to all tds then use this line
    $(this).closest("tr").find("td").attr("your-attribute", "value");

    //if you want to add attribute to all tds except the first one then use this line
    $(this).closest("tr").find("td:not(.sorting_1)").attr("your-attribute", "value");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM