2012-05-29 75 views
0

我收到了一個意外的錯誤,其中有一個令人討厭的時間調試。 我得到的錯誤是這樣的:爲什麼我無法將jQuery選擇器對象從內聯HTML元素傳遞給函數?

Uncaught SyntaxError: Unexpected token }

這是HTML:

<html> 
<head> 
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
</head> 
<body> 

<form class="search" action="search" method="get"> 
<input type="text" id="search-string" /> 
<button type="button" onclick="return clearInputValue($("#search-string"))"> 
<span class="clear-icon"></span> 
</button> 
</form> 

<script> 
var clearInputValue = function(a) { 

// Ultimately I will check if the object passed to this function has a value greater than 1, and if so, I will clear the input 

    return false; 

}; 

</script> 


</body> 
</html> 

回答

2

您需要使用一組不同的報價。

<button type="button" onclick="return clearInputValue($('#search-string'))"> 

請注意單引號。

另外,作爲一個附註,內聯javascript是不鼓勵的。將您的內容(html)與您的行爲(javascript)分開會更好,就像您對演示文稿(css)所做的一樣。

2

其中之一,你剛剛結束了字符串。將其更改爲:

onclick="return clearInputValue($('#search-string'))" 

其次,您應該使用jQuery附加事件。

$(function(){ 

    function clearInputValue(a) { 
     return false; 
    }; 


    $('button').on('click',function(){ 
     clearInputValue($('#search-string')); 
    }); 

}); 
相關問題