文档.写的问题

Document.write issues

本文关键字:问题 文档      更新时间:2023-09-26

我正在制作一个页面,用户可以在其中回答有关他们正在销售的产品的问题(使用单选按钮)。当他们点击页面底部的按钮时,会弹出一个报价。我写了一个javascript函数,当用户点击按钮时执行。它计算价格并使用document显示。写,但每当用户点击按钮,它打开一个新的页面,并显示我告诉它的内容。

function getQuote(){
    document.write("Your Quote Is: $", price, ".00");
}

下面是按钮的代码:

<button type="button" onclick='getQuote()'>Display Quote</button>

但是当我按下按钮时,一个新页面出现了,它只显示了我放入document.write短语的格式。

我已经尝试使用.innerHTMLdocument.write发送到页面的另一部分,但同样的问题仍然存在。

我能做些什么来确保引用显示在我想要的页面上?

document.write没有问题,它正在做它应该做的事情:

用新内容覆盖该页。

如果你不想这样做,那么你必须给它一些上下文来写。

例如:

function getQuote(){
    var textArea = document.getElementById('textArea');
    textArea.innerHTML = "Your Quote Is: $", price, ".00";
}

将你的文本放入一个DOM元素id="textArea"

在你的文档完全渲染并关闭后,使用document.write()将清除当前文档并开始一个新文档,清除所有以前的内容。

将内容放入现有文档中需要使用DOM操作函数,而不是document.write()。如果你想改变按钮的文本,你可以这样做(假设price是一个包含价格的全局变量):

<button type="button" onclick='getQuote(this)'>Display Quote</button>
function getQuote(obj) {
    obj.innerHTML = "Your Quote Is: $" + price + ".00";
}

如果你想把价格输入到页面上的其他对象中,然后给那个对象一个id你就可以获取那个对象并像这样设置价格:

<button type="button" onclick='getQuote()'>Display Quote</button>
<div id="quotedPrice"></div>
function getQuote() {        
    document.getElementById("quotedPrice").innerHTML = "Your Quote Is: $" + price + ".00";    
}

你可以在这里看到这两个论坛的工作:http://jsfiddle.net/jfriend00/ED5V9/

您应该引用元素,并设置其内容,而不是使用document.write

<button type="button" onclick='getQuote.call(this)'>Display Quote</button>

function getQuote(){
     this.firstChild.data = "Your Quote Is: $" + price + ".00";
}

如果您想写入一个不同的元素,您应该选择该元素,并可能使用相同的技术。