4

我有一个小计算器,要添加到我的 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?这就是我在stockoverflow上从其他人那里得到的,但我还是有点困惑

4

3 回答 3

12

您的输出需要一个占位符元素。然后为该元素设置innerHTML:

<div id='answer'></div>

然后:

document.getElementById('answer').innerHTML = "answer is:" + yourdata
于 2012-08-10T18:16:46.033 回答
4

不要使用 document.write,句号。使用 DOM 操作:http ://www.quirksmode.org/dom/intro.html

于 2012-08-10T18:15:02.117 回答
2

而不是document.write()您可以设置innerHTML任何 DOM 节点的属性来向页面添加文本。

假设您将 a 添加<div id='result'></div>到页面末尾(在 body 标记之前)。然后在你的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
}
于 2012-08-10T18:15:15.253 回答