我有一个小计算器,我正在添加到我的HTML中。它有几个下拉菜单来选择东西,当一个人点击提交按钮时,我想在我的HTML中显示计算器下面的图片。我尝试使用javascript函数:document.write()但是清除了整个页面。有没有办法让我可以运行一个javascript函数,只有在点击提交按钮时才会将图片添加到我的页面?
以下是我的代码的基本概要,其中包含我遇到问题的部分:
<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>
是否可以使用某种内部HTML?这就是我在库存溢出时从别人那里得到的,但我仍然有点困惑
答案 0 :(得分:6)
您的输出需要占位符元素。然后为该元素设置innerHTML:
<div id='answer'></div>
然后:
document.getElementById('answer').innerHTML = "answer is:" + yourdata
答案 1 :(得分:4)
不要使用document.write,period。使用DOM操作:http://www.quirksmode.org/dom/intro.html
答案 2 :(得分:1)
您可以设置任何DOM节点的document.write()
属性来向页面添加文本,而不是innerHTML
。
假设您在页面末尾(正文标记之前)添加<div id='result'></div>
。然后在你的javascript中有:
var result_display = document.getElementById('result');
// and in calc_rate():
result_display.innerHTML = "answer";
请注意,这将始终重置result_display的文本。您还可以将该操作包装在函数中:
function displayResult(result){
result_display.innerHTML = '<h2>' + result + '</h2>'; // or whatever formatting
}