javascript - 使用 Jquery .after() 移动元素

标签 javascript jquery html jquery-after

我正在阅读 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/

相关文章:

javascript - CSS bootstrap 多个弹出框的不同定位

javascript - 如何使用 ASP.Net 中的 PageMethods 将多维数组从 Javascript 传递到服务器

javascript - 每个图像缩略图预览的删除按钮

jquery - 禁用和启用 div 事件处理程序单击 jQuery?

html - 在 Bootstrap 工具提示中强制换行

javascript - ng-show 和 ng-if 无法显示内容

javascript - 输入时动画不起作用(Tailwind、TransitionGroup、Typescript)

javascript - 使用事件监听器捕获变量

html - 如何在网站中使用自定义字体

html - 居中图像在水平和垂直方向上都充当 "popup"