我不知道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
有人能指点我正确的方向吗?提前谢谢!
答案 0 :(得分: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>
答案 1 :(得分:1)
你需要抓住innerHTML
并设置它:
var elem = document.getElementById('demo').innerHTML;
document.write(elem);
请注意,document.write
将覆盖所有内容。
答案 2 :(得分:1)
您将elem
设置为setAttribute
的返回值,该值未定义,因为它不返回任何内容。
将代码更改为:
var elem = document.getElementById('demo');
elem.setAttribute('id', 'nextstep');
document.write(elem.innerHTML);
示例 - http://jsfiddle.net/P8EcL/
这仍然不会完全符合您的要求,因为它是p标签内容的副本而不是标签本身。
Scott Mermelstein's回答是你想要的。
答案 3 :(得分: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>
答案 4 :(得分:0)
var elem = document.getElementById('demo').innerHTML;
document.write(elem);
我不确定你为什么要尝试在原始div上设置一个新的id并期望它返回HTML,但它不会起作用;)