jquery,获取元素,然后在它之前复制某个类

时间:2014-01-12 11:17:25

标签: jquery

要编辑的示例页面:

reply link
post

reply link
post

reply link
post

我希望每个帖子都能复制回复链接并附加到帖子中。然后我删除回复链接。

var elements = document.getElementsByClassName('postMessage');

for (var n = elements.length; n--> 0;) 
{
    var elementi = $(".replylink" ).clone();

    elements[n].innerHTML += elementi;

}

这不会起作用

1 个答案:

答案 0 :(得分:0)

elements[n].innerHTML+=elementi; text 操作。您最终会在页面上显示[object Object]

听起来你想要移动回复链接。如果是这样,只需使用jQuery的append(如果元素已经在页面的其他位置,它将移动该元素):

$(".postMessage").each(function() {
    var $this = $(this);
    var replylink = $this.prevAll(".replylink").first();
    $this.append(replylink);
});

棘手的位是$this.prevAll(".replylink").first(),它执行此操作:

  • 按照从最近的帖子到最远的顺序,构建一个之前这个.replylink元素的所有.postMessage个元素的列表。
  • 取第一个,即最接近.postMessage的那个。

完整示例:Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Example</title>
  <style>
    .postMessage {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <p>In a second, the reply links will move <em>into</em> the posts.</p>
  <a href="#" class="replylink">reply 1</a>
  <div class="postMessage">I'm post 1&nbsp;</div>
  <a href="#" class="replylink">reply 2</a>
  <div class="postMessage">I'm post 2&nbsp;</div>
  <a href="#" class="replylink">reply 3</a>
  <div class="postMessage">I'm post 3&nbsp;</div>
  <script>
    setTimeout(function() {
      $(".postMessage").each(function() {
        var $this = $(this);
        var replylink = $this.prevAll(".replylink").first();
        $this.append(replylink);
      });
    }, 1000);
  </script>
</body>
</html>
相关问题