问题
I have a small calculator that I'm adding to my html. It has a few dropdowns to select stuff and when a person hits a submit button, I'd like to display a picture below the calculator in my html. I've tried using a javascript function with: document.write() but that clears the whole page. Is there a way that I can get a javascript function to run which only adds a picture to my page when a submit button is clicked?
Here's a BASIC outline of my code with the part I'm having trouble with:
<html>
<head>
<script type="text/javascript">
function calc_rate() {
//code that displays a message after the submit button is hit
document.write("answer");
}
</script>
</head>
<body>
<table>
<tr>
<td class=rate_calc_label>Select Your Option Type:</td>
<td><select name="type1">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select></td>
</tr>
<tr>
<td class=rate_calc_label>Select The Second Number:</td>
<td><select name="type2">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select></td>
</tr>
<tr>
<td><input type="submit" value="Submit" name="calc_button" onclick="calc_rate()"/></td>
<td></td>
</tr>
</table>
</body>
</html>
would it be possible to use some kind of inner-HTML? That's what I got from others on stockoverflow but I'm still a little confused
回答1:
You need a placeholder element for your output. Then set the innerHTML for that element:
<div id='answer'></div>
then:
document.getElementById('answer').innerHTML = "answer is:" + yourdata
回答2:
Don't use document.write, period. Use DOM operations: http://www.quirksmode.org/dom/intro.html
回答3:
Instead of document.write()
you can set the innerHTML
property of any DOM node to add text to the page.
Say you add a <div id='result'></div>
to the end of the page (before the body tag). Then in your javascript have:
var result_display = document.getElementById('result');
// and in calc_rate():
result_display.innerHTML = "answer";
Note that this will always reset the result_display's text. You can also wrap that operation in a function:
function displayResult(result){
result_display.innerHTML = '<h2>' + result + '</h2>'; // or whatever formatting
}
来源:https://stackoverflow.com/questions/11907053/how-do-i-add-something-to-my-html-using-javascript-without-erasing-the-whole-pag