2012-08-10 46 views
3

我有一個小型計算器,我將它添加到我的html中。它有幾個下拉列表來選擇內容,當一個人點擊一個提交按鈕時,我想在我的html中的計算器下面顯示一張圖片。我試過使用一個JavaScript函數:document.write(),但清除整個頁面。有沒有一種方法,我可以得到一個JavaScript函數運行,只有當點擊一個提交按鈕時纔會將圖片添加到我的頁面?如何在不刪除整個頁面的情況下使用javascript添加內容到我的html中

這裏是我與我遇到的麻煩的部分代碼基本輪廓:

<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上獲得的其他人,但我仍然有點困惑

回答

6

您需要一個佔位符元素用於輸出。然後設置innerHTML的該元素:

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

則:

document.getElementById('answer').innerHTML = "answer is:" + yourdata 
+0

這工作就像一個魅力!我能夠像你說的那樣創建一個空白的div,然後添加代碼以便進入該圖片。 – 2012-08-10 20:40:42

1

而不是document.write()您可以設置任何DOM節點的innerHTML屬性添加文本到頁面。

假設您將一個<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 
} 
相關問題