2014-01-12 31 views
2

嘗試將this.value作爲參數傳遞時,我不斷收到意外的代碼}錯誤。Javascript:意外的代幣}

在我的身上,我有:

<input type="text" size="3" id="rbgTextbox" onkeypress="if (ValidateRGBTextboxInput(event)) ChangeBackgroundColor("+this.value+"); else return false;"> 

功能:

<script type="text/javascript"> 
    function ValidateRGBTextboxInput(e) { 
     return ById('rbgTextbox').value.length < 6 && 
     (e.which >= 48 && 
     e.which <= 57 || 
     e.which >= 65 && 
     e.which <= 70 || 
     e.which >= 97 && 
     e.which <= 102); 
    } 

    function ChangeBackgroundColor(color) { 
     alert(color); 
     ById('gameArea').style.backgroundColor = '#'+color; 
     ById('nextPiece').style.backgroundColor = '#'+color; 
    } 
    </script> 

如果我改變ChangeBackgroundColor( 「+ THIS.VALUE +」);爲ChangeBackgroundColor('000000');我沒有得到更多的錯誤,但我當然需要傳遞文本輸入的值作爲參數。

回答

2

你不需要引號。如果您有雙引號,則會破壞輸入字段上onkeypress屬性所需的字符串。希望是有道理的;)

<input type="text" 
     size="3" 
     id="rbgTextbox" 
     onkeypress="if (ValidateRGBTextboxInput(event)) ChangeBackgroundColor(this.value); else return false;"> 

popular post on SO可以幫助您瞭解在Javascript報價。

1

嘗試將if語句放在函數中並調用該函數。它會實現一些事情。它讓你的代碼更具可讀性,並且可以讓你輕鬆地在你的if和else裏面放置一些警報,看看實際發生了什麼。

1

我不認爲你需要+ this.value +'語句只是this.value。

此外,我建議你只是添加一個點擊處理程序的HTML和避免其他邏輯如下所示。

http://jsfiddle.net/9BtAM/13/

注意,我認爲你的設計需要的元素值未設置按鍵事件後,直到進一步提高。因此,如果可以接受現有的元素值,則需要連接新的按鍵。

<input type="text" size="3" id="rbgTextbox" onkeypress="CheckKeyPress(event);" /> 

隨着這裏

function CheckKeyPress(event) { 
    var element = document.getElementById('rbgTextbox'); 

    if (ValidateRGBTextboxInput(keyPressEvent)) 
     ChangeBackgroundColor(element.value); 
    else 
     return false; 
} 

的JavaScript哪個更容易跟蹤。作爲一項規則,你不需要直接在html中使用複雜的JavaScript。

+1

除了在IE瀏覽器(以及像IE瀏覽器那樣將瀏覽器特定代碼投入骨骼之類的瀏覽器)之外,'event'的使用將無法使用。此外,您調用'CheckKeyPress'的方式,'this'不會是元素引用(它將成爲全局對象)。 –

相關問題