2

関数に関するjqueryのマニュアルを読んでい.after()ます:

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

そしてそれは言う

「この方法で選択した要素を他の場所に挿入すると、複製されるのではなく移動されます」

だから私が複数ある場合 <div class='before' onclick='afterfunction();'><div>

<div class='after'></div>divがクリックされた後に配置したい(クローンではなく移動する)このようなことをしますか?

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

ご協力ありがとうございます!

4

2 に答える 2

3

あなたが言ったように:

DOM内の要素を選択して、別の要素の後に挿入することもできます 。$('。container')。after($('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()(ここの答えで間違って提案されたように)。

デモjsFiddle

于 2012-05-16T20:00:32.527 に答える
1

このようにdiv.beforeを作成します:

<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
}

デモ

于 2012-05-16T19:43:47.867 に答える