2014-01-12 40 views
-2

例如網頁編輯之前某一類權: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; 

} 

這不會工作

回答

0

elements[n].innerHTML+=elementi;文本操作。您最終會在您的網頁上顯示[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> 
相關問題