2013-11-27 79 views
7

我是新來的JavaScript,並作爲大學裏的項目的一部分,我需要包括一些。我創建了一個簡單的.js文件並將其鏈接到使用<script src="main.js"></script>遺漏的類型錯誤:字符串不是一個函數

我創建了一個名爲sellYourHome.html另一頁,並增加了<section>標籤有一張桌子和創建了一個簡單的表格,計算comission,並將結果顯示回我的index.html文件在輸入字段中。

function comCalc() 
{ 
prcHouse = parseFloat(document.getElementById('prcHouse').value); 
commision = 0.25; 
result = prcHouse * commision; 
document.getElementById('prcHouse').value = result.toString(); 
} 

工作。

現在在這個函數下,我想創建另一個元素,它拾取一個<div>元素並將background-color更改爲藍色。

所以我創建了一個index.html形式和以同樣的方式連接的同一個.js文件給它。

這是我的HTML:

<div id="mainContent"> 
    <p>hello</p> 
    <form id="bgColor"> 
     <table> 
      <tr> 
       <td> 
        <input type="button" value="blue" onclick="bgColor('blue');"> 
       </td> 
      </tr> 
     </table> 
    </form><!-- end of bgColor Form--> 
</div> 

我的JavaScript像這樣:

function comCalc() 
{ 
    prcHouse = parseFloat(document.getElementById('prcHouse').value); 
    commision = 0.25; 
    result = prcHouse * commision; 
    document.getElementById('prcHouse').value = result.toString(); 
} 

function bgColor(color) 
{ 
    var div = document.getElementById('mainContent'); 
    div.style.background=color; 
} 

當我運行它,我得到的控制檯上的錯誤:

Uncaught TypeError: String is not a function

我我在一個叫SWRIron瀏覽器中運行的(這是基於瀏覽器和HTML5是-complient)。

我在做什麼錯?

+6

我不會在任何地方看到任何'sting' – Brian

+0

我的朋友在兩個實例中輸入錯字=「String」 – StudentwebCoding

回答

5

這是因爲你的函數名bgColor的,因爲bgcolorHTML元素的屬性,它與你的函數bgcolor,瀏覽器將發生衝突以此爲attribute(串),但你用它作爲一個功能,所以它說string is not a function。因此,該功能的名稱更改爲別的像這樣

function setBgColor(color) 
{ 
    var div = document.getElementById('mainContent'); 
    div.style.background = color; 
} 

使用它作爲

<input type="button" value="blue" onclick="setBgColor('blue');" /> 

Example.

+0

謝謝,完美無缺! – StudentwebCoding

+0

@StudentwebCoding,歡迎您:-) –

+3

正確答案等等....? – Celt

0

是。由於博客上的系統保留HMTL,它拋出所謂錯誤「遺漏的類型錯誤:字符串是不是一個函數」。如果您更改方法名稱,它將正常工作並正常工作。

+0

這不會給對方的回答添加任何東西。 – Scimonster

相關問題