使用Jquery .after()来移动元素

时间:2012-05-16 19:37:48

标签: javascript jquery html jquery-after

我正在阅读有关.after()功能的jquery manual

$('.container').after($('h2'));

它说

  

“如果以这种方式选择的元素插入其他地方,它将会是   移动而不是克隆“

所以,如果我有多个 <div class='before' onclick='afterfunction();'><div>

我希望在点击任何div之后放置<div class='after'></div>(让它移动,而不是克隆)我会做这样的事情吗?

var afterdiv = "<div class='after'></div>";
function afterfunction() {
    $(this).after(afterdiv);
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

就像你说的那样:

  

也可以在另一个元素之后选择并插入DOM中的元素:   $(”。容器 ')后($(' H2' ));
  如果以这种方式选择的元素插入其他地方,   它将被移动而不是克隆:

但是你错过了大胆的部分。

$('.before').click(function() {
  afterfunction(this);
});

// this will not work cause you'll append a string to your DOM
// var afterdiv = "<div class='after'>ola</div>";
// and will repeatedly be appended after each action.

// instead define your element by wrapping it into a $( )
  var afterdiv = $("<div class='after'>ola</div>");
// now 'afterdiv' variable is binded to that element only once inside the DOM 

function afterfunction(elem) {
   $(elem).after(afterdiv);
}

你不需要.remove()它(就像在这里的答案中错误地建议的那样。)

demo jsFiddle

答案 1 :(得分:1)

像这样制作.before div:

<div class='before'><div/>

然后试试,

$('.before').on('click', function() {
  afterfunction(this);
});

function afterfunction(el) {
  var afterdiv = "<div class='after'></div>";
  $('.after').remove(); // remove previous `.after`
  $(el).after(afterdiv); // add newly after the clicked div
}

<强> DEMO