2011-09-21 26 views
0

我試圖用'.comments'內的值創建一個變量,然後在'4個評論'前加上'Read all'一詞。最後,將新變量附加到'#comments'。如何使用JavaScript克隆,更新和追加變量

管理寫東西,但它移動現有的對象,而不是創建一個新的對象與現有的價值。

下面

<script type="text/javascript"> 
var commentsLink = document.querySelector('.story .comments a'),  
    commentsSubmit = document.querySelector('#comments .form-item-submit'); 
commentsLink.innerHTML = 'Read all ' + commentsLink.innerHTML; 
commentsLink.className += 'readComments'; 
commentsSubmit.appendChild(commentsLink); 
</script> 

<div class="story"> 
    <div class="comments"> 
      <a href="http://foo.com">4 comments</a> 
    </div> 
</div> 
<div id="comments"> 
    <div class="form-item-submit">Submit</div> 
</div> 

一些代碼期望的結果:

<div class="story"> 
    <div class="comments"> 
      <a href="http://foo.com">4 comments</a> 
    </div> 
</div> 
<div id="comments"> 
    <div class="form-item-submit">Submit</div> 
    <a href="http://foo.com" class="readComments">Read all 4 comments</a> 
</div> 

任何人都可以闡明這一些輕?請不要Jquery。

回答

1
  1. 要複製元素,請使用cloneNode。要複製文本內容,請使用cloneNode(true)
  2. 您希望將克隆的鏈接附加在提交div父級元素上,而不是在提交div本身內。

http://jsfiddle.net/eDGwj/

var commentsLink = document.querySelector('.story .comments a').cloneNode(true), 
    commentsSubmit = document.querySelector('#comments .form-item-submit'); 

commentsLink.innerHTML = 'Read all ' + commentsLink.innerHTML; 
commentsLink.className += 'readComments'; 

commentsSubmit.parentNode.appendChild(commentsLink); 
0

事情是這樣的:

<script type="text/javascript"> 
var commentsLink = document.querySelector('.story .comments a'),  
    commentsSubmit = document.querySelector('#comments .form-item-submit'), 
    anchor = commentsLink.cloneNode(false); 

anchor.innerHTML = 'Read all ' + commentsLink.innerHTML; 
anchor.className += ' readComments'; 

commentsSubmit.parentNode.appendChild(anchor); 
</script> 
0

我想這是你想要的,如果不是請評論:

<script type="text/javascript"> 
    var commentsLink = document.querySelector('.story .comments a'),  
     commentsSubmit = document.querySelector('#comments .form-item-submit'); 
    var cloneLink = commentsLink.cloneNode(true); 
    cloneLink.innerHTML = 'Read all ' + commentsLink.innerHTML; 
    cloneLink.className += 'readComments'; 
    commentsSubmit.appendChild(cloneLink); 
</script> 

的關鍵功能是cloneNode(),注意與標識的

More Info

希望這會有所幫助