简体   繁体   English

如何将元素移到下一个兄弟姐妹?

[英]How to move an element to its next sibling?

I'm trying to grab an element and move it to its next sibling while at the same time adding attributes to that next sibling. 我试图获取一个元素并将其移至下一个兄弟姐妹,同时向该下一个兄弟姐妹添加属性。 How do I do that in jQuery? 如何在jQuery中做到这一点?

Specifically, I want to move the "span" inside the "a" tags below, and add an "data-toggle='tooltip'" and 'title="SOMETHING HERE"' attributes to that "a" tag. 具体来说,我想将“ span”移动到下面的“ a”标签内,并向该“ a”标签添加"data-toggle='tooltip'"'title="SOMETHING HERE"'属性。

Thus this: 因此:

<td>
  <span>Total partners</span>
  <a id="answer_view_2_list_row_7"></a>
</td>

would become this: 会变成这样:

<td>
  <a id='answer_view_2_list_row_7' data-toggle='tooltip' title='SOMETHING HERE'>
    <span>Total partners</span>
  </a>
</td>

Any help appreciated. 任何帮助表示赞赏。 I'm learning jQuery but this one is beyond me. 我正在学习jQuery,但是这一本书超越了我。

It would be something like: 就像这样:

// Append to `a` tag.
$('span').appendTo('a');
// Add attributes.
$('a').attr({
    'data-toggle':'tooltip',
    'title':'SOMETHING HERE'
});

Or better yet: 或者更好:

$('span').each(function() {
    $(this).next().attr({
        'data-toggle':'tooltip',
        'title':'SOMETHING HERE'
    });
    $(this).appendTo($(this).next());
});

Fiddle 小提琴

$('td a').append(function () {
    return $(this).parent().find('span')
}).data('toggle', 'tooltip').attr('title', 'SOMETHING HERE')

jsFiddle example jsFiddle示例

Note that you won't see the data attribute in the source as it's stored internally. 请注意,您不会在源中看到data属性,因为它是内部存储的。

$('td > a').attr({
    'data-toggle': 'tooltip',
    'title': 'something here'
}).append($('td > span'));

尝试这样的事情:

$('myelement').each(function() { $(this).appendTo($(this).next()); });

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

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