我正在阅读 jquery manual关于.after()
功能:
$('.container').after($('h2'));
它说
"If an element selected this way is inserted elsewhere, it will be moved rather than cloned"
所以如果我有多个
<div class='before' onclick='afterfunction();'><div>
,
我想放置 <div class='after'></div>
单击哪个 div 后(让它移动,而不是克隆)我会做这样的事情吗?
var afterdiv = "<div class='after'></div>";
function afterfunction() {
$(this).after(afterdiv);
}
感谢您的帮助!
最佳答案
就像你说的:
An element in the DOM can also be selected and inserted after another element: $('.container').after($('h2'));
If an element selected this way is inserted elsewhere, it will be moved rather than cloned:
但是你错过了粗体部分。
$('.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
关于javascript - 使用 Jquery .after() 移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625501/