2

我不知道javascript,我一直在到处寻找这个答案。我想在我的页面中复制内容。html 和内容直接来自代理。

想要的结果是:

Click the button to change the text in this paragraph.
Click the button to change the text in this paragraph.

我的 HTML 是:

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
var elem = document.getElementById('demo').setAttribute('id', 'nextstep');
document.write(elem);
</script>
</body>
</html>

我得到的是:

Click the button to change the text in this paragraph.
undefined

有人可以帮我指出正确的方向吗?提前致谢!

4

5 回答 5

3

我不相信你想使用 document.write。我想这就是你所追求的:

<script language="javascript" type="text/javascript">
    // this gets the element
    var elem = document.getElementById('demo'); 
    // this copies the entire element, including the id
    var newElem = elem.cloneNode(true); 
    // this sets a new id
    newElem.setAttribute('id', 'nextstep');
    // generic way to make sure you insert properly
    var before = elem.nextSibling;
    // there's no insertAfter, only insertBefore, which is why we found the before
    elem.parentNode.insertBefore(newElem, before);
</script>

小提琴

于 2013-09-25T14:58:57.670 回答
1

你需要抓住innerHTML并设置它:

var elem = document.getElementById('demo').innerHTML;
document.write(elem);

不过要小心,document.write会覆盖所有内容..

于 2013-09-25T14:53:23.580 回答
1

您正在设置elem的返回值setAttribute是未定义的,因为它不返回任何内容。

将代码更改为:

var elem = document.getElementById('demo');
elem.setAttribute('id', 'nextstep');
document.write(elem.innerHTML);

示例 - http://jsfiddle.net/P8EcL/

这仍然不能完全符合您的要求,因为它是 p 标签内容的副本,而不是标签本身。

Scott Mermelstein 的答案就是你想要的。

于 2013-09-25T14:53:33.750 回答
1

如果你需要得到这个

<p id="demo">Click the button to change the text in this paragraph.</p>
<p id="nextstep">Click the button to change the text in this paragraph.</p>

尝试

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script language="javascript" type="text/javascript">
    var elem = document.getElementById('demo');
    var newElem = document.createElement('div');
    newElem.innerHTML = "<p id='nextstep'>" + elem.innerHTML + "</p>";
    document.write(newElem.innerHTML);
</script>
</body>
</html>
于 2013-09-25T15:07:20.753 回答
0
var elem = document.getElementById('demo').innerHTML;
document.write(elem);

我不确定您为什么要尝试在原始 div 上设置新 id 并期望它返回 HTML,但它不起作用;)

于 2013-09-25T14:53:42.950 回答