Document.write issues

前端 未结 3 499
借酒劲吻你
借酒劲吻你 2021-01-24 05:27

I am making a page where users can answer questions (using radio buttons) about a product they are selling back. When they hit a button at the bottom of the page, a price quote

相关标签:
3条回答
  • 2021-01-24 06:01

    After your document has been full rendered and closed, using document.write() will clear your current document and start a new one, wiping out all previous content.

    The put content into the existing document you need to use DOM manipulation functions, not document.write(). If, what you're trying to do is to change the text of your button, you can do so like this (assuming price is a global variable that contains the price):

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

    If you want to put the price into some other object on the page, then you give that object an id and you can get that object and set the price into it like this:

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

    You can see both forums of these work here: http://jsfiddle.net/jfriend00/ED5V9/

    0 讨论(0)
  • 2021-01-24 06:03

    You should reference the element, and set its content instead of using document.write.

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

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

    If you want to write to a different element, you should select that element, and likely use the same technique.

    0 讨论(0)
  • 2021-01-24 06:08

    There is no issue with document.write, it is doing exactly what it is supposed to do:

    Overwrite the page with the new content.

    If you do not want to do that, then you have to give it some context to write to.

    For example:

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

    Which puts whatever your text is into a DOM element with id="textArea"

    0 讨论(0)
提交回复
热议问题