0

我正在尝试使用“.comments”中的值创建一个变量,然后在“4 个评论”之前添加“阅读全部”一词。最后,将新变量附加到“#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。

4

3 回答 3

1
  1. 要克隆元素,请使用cloneNode. 要同时复制文本内容,请使用cloneNode(true).
  2. 您希望将克隆的链接附加到 submit 的元素div,而不是 submitdiv本身。

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);
于 2011-09-21T07:44:42.933 回答
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>
于 2011-09-21T07:43:38.050 回答
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 的

更多信息

希望这可以帮助

于 2011-09-21T07:44:27.800 回答