2017-04-06 96 views
-3

我目前正在學習JavaScript。我在Web上沒有什麼經驗。請原諒我這個問題。javascript onclick不能調用函數

我想使用onclick事件來函數。不幸的是,它不加載函數。

<img id="btnPartDispatch" title="sometitle" class="img-rounded" src="~/Content/Images/dashboard/PartDispatch.png" width="115" height="115" onclick="HelloWorld()" /> 

功能是在不同的文件中:

function HelloWorld(){ 
alert"('hello world')" 
} 

但是,如果我改變onclick事件提醒( 「Hello World」 的),它工作正常。 是這樣的:

<img id="btnPartDispatch" title="sometitle" class="img-rounded" src="~/Content/Images/dashboard/PartDispatch.png" width="115" height="115" onclick="alert('Hello World!')" /> 

有人能告訴我我做錯了什麼嗎? 感謝

獲取有關這樣的JavaScript文件:

@section scripts 
{ 
    <script type="text/javascript"> 
     var secondsToClosePopup = 1000 * @Functions.GetNumberOfSecondsToClosePopup(); 
    </script> 
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.multiple.select.js")"></script> 
    <script type="text/javascript" src="@Url.Content("~/Scripts/service.js")"></script> 
} 

項目是ASP.net

+2

第一個版本應該產生一個'SyntaxError' – Andreas

+0

我們需要知道你是如何在HelloWorld功能導入文件。 – Potray

+0

你必須有,如果作爲一個功能。 'alert()'。你也有其他選擇。通過Id事件偵聽器使用get元素。 –

回答

0

你必須從這個刪除雙引號:

alert"('hello world')" 

alert('hello world') 
0

alert"('hello world')"將拋出語法錯誤,因爲它必須alert('hello world');


爲什麼它必須是

alert or window.alert是一個顯示瀏覽器默認對話框的函數。

自一function,你將有其名稱後添加()調用它,並通過必要的參數(消息),它預計。因此,alert('hello world')

另外,作爲一個方面說明,由於您在HTML中綁定了onclick,請確保在加載DOM之前加載了您的函數。否則它會拋出錯誤。

+0

我只是想知道這是否應該被視爲印刷錯誤? – Rajesh

+0

我認爲它是如何使用函數的一個誤解 – Rajesh

+0

@Justinas,我已經更新了你的答案,因爲OP是初學者。如果不需要,請將其還原,或者如果有任何信息不正確,請糾正。 :-) – Rajesh

0

你的語法調用警報的方法是錯誤的。您可以使用它像這樣

<html> 
<body> 
<button onclick="HelloWorld()">Click me</button> 
<script> 
function HelloWorld() { 
    alert("Hello World"); 
} 
</script> 
</body> 
</html> 
+0

請參閱其他答案,因爲此糾正已在其他答案中解決,這將是重複。會請求您添加其他人未解決的問題或刪除您的答案 – Rajesh