2013-03-21 37 views
0

我試圖在包裹在錨點中的div中輸出我的值。基本上,有人打出了他想要的高度,並且給了他等同的數據表。如何在包含錨點的div中輸出我的值javascript

我不能解決如何輸出我想在包裹在一個錨點div的字符串的方式。

這裏是我的代碼:

<form name="test"> 
<label for="height">Height</label> 
    <input type="text" name="height" /><br> 
    <label for="width">Width</label> 
<input type="text" name="width" /><br> 
<label for="depth">Depth</label> 
<input type="text" name="depth" /><br> 
<label for="load">Load</label> 
<input type="text" name="load" /><br> 
    <input type="button" onclick="calculate();" value="Calculate" /><br><br> 



</form> 
<div id="result"> 
</div> 

      <script type="text/javascript"> 
         function calculate() 
         { 
          var height = document.test.height.value; 
          if (height <= 525) { 
           var str = "Download your Datasheet 1"; 

          } 
          else if (height < 645) { 
           var str = "Datasheet 2"; 

          } 

          else if (height > 1265) { 
           var str = "This configuration is beyond the standard range of top-load testers. Please contact Mecmesin Sales to discuss ways to meet your requirements."; 
          } 

          else if (isNaN(height)) { 
           window.alert(height + ' is not a number!'); 
           } 

          else { 
           var str = "Datasheet 3"; 
          } 
          document.test.result.value = str.anchor(); 

         } 
      </script> 

在此先感謝。

回答

0

我認爲其他人已經錯過了讓div包含一個錨點......這將表明你需要提供一個url和一個字符串,但是一旦你完成了額外的代碼更換document.test.result.value線應該是這個樣子:

// empty out the result div first 
var node = document.getElementById('result'); 
while(node.firstChild) { 
    node.removeChild(node.firstChild); 
} 

// create the anchor DOM object 
var a = document.createElement('a'); 
var linkText = document.createTextNode(str); 
a.appendChild(linkText); 
a.title = str; 
a.href = "http://example.com/"+str+".pdf"; //for example 

// attach it to your result node 
node.appendChild(a); 

如果你不重用的頁面而不刷新它打算,你可以不用while循環。

+0

是的,但我可以做到這一點,我可以嗎? var str ='Download your Datasheet 1'; – Codeninja 2013-03-21 16:06:40

+0

你可以,但建議習慣直接處理dom。這更有趣,尤其是當你使用像Dojo這樣的框架時...... – Radiotrib 2013-03-21 16:09:04

+0

哇!真的很有趣我不得不說...感謝百萬... – Codeninja 2013-03-21 16:13:33

0

試試這個:

document.getElementById("result").innerHTML = str; 
+0

您的回答是正確的,但下面解釋更好:)謝謝 – Codeninja 2013-03-21 16:00:04

0
var height = document.test.height.value 

此行是不是給你的形式高度的價值。

給該輸入像「高度」的ID,然後得到是這樣的值:

var height = document.getElementById('height').value; 

您不能訪問元素作爲文檔對象像你正在嘗試做的屬性,你需要選擇其中使用類似document.getElementById或document.getElementByTagName

+1

謝謝你的伴侶! – Codeninja 2013-03-21 16:00:36

0

您沒有正確使用DOM。

你需要給一個ID爲height輸入:

<input type="text" id="height" name="height" />
var height = document.getElementById("height").value;


或者你可以簡單地使用:

var height = document.getElementsByName("height")[0].value;

,但我不會建議。

+0

謝謝以及:) – Codeninja 2013-03-21 16:01:37