你如何克隆,更新和使用JavaScript附加变量

时间:2011-09-21 06:55:29

标签: javascript variables clone appendchild

我正在尝试使用'.comments'中的值创建一个变量,然后在'4 comments'前面加上'Read all'这个词。最后,将新变量附加到'#comments'。

管理写东西,但它正在移动现有对象,而不是创建一个具有现有对象值的新对象。

下面的一些代码

<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。

3 个答案:

答案 0 :(得分:1)

  1. 要克隆元素,请使用cloneNode。要复制文本内容,请使用cloneNode(true)
  2. 您希望克隆的链接附加在提交div元素中,而不是在提交div本身内。
  3. 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);
    

答案 1 :(得分: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>

答案 2 :(得分: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(),请注意Id的

More Info

希望这有帮助