2017-04-20 65 views
1

我試圖直接在我的按鈕屬性onclick中使用一個函數,但我總是有錯誤。 例子:如何在onclick按鈕寫屬性attribut

<button onclick="function() { alert('hello'); }">Click me</button> 

,其結果是:

Uncaught SyntaxError: Unexpected token (

+2

JavaScript和Java有很少共同點。刪除java標籤! –

+0

你所要做的就是* define *一個函數,它不會明顯地完成任何事情。只需調用你想要調用的代碼:'onclick =「alert('hello')」'如果你想定義一個函數,請在你的JavaScript代碼中單獨執行,然後在'onclick'中調用該函數。 (或者,甚至更好的是,將它作爲JavaScript代碼的處理程序附加,因此您不會在HTML中編寫內嵌JavaScript。) – David

回答

1

沒有必要使它成爲一個功能,只需列出聲明:

<button onclick="alert('hello');alert('hello 2');alert('hello 3');">Click me</button> 
+0

這只是一個示例,我有一個複雜的代碼,並且在onclick中有一個ajax調用,但錯誤總是相同的 – Storm

+0

好的,你可以更新你的問題,以更好地反映你的特殊情況。仍然。你爲什麼要使用內聯函數?還有很多其他的模式可以使用 – user5328504

0

下面的代碼將允許您添加功能在你的onclick屬性中。

點擊我

<button onclick="javascript:(function() { alert('hello'); })()">Click me</button>

0

你應該寫你這樣的代碼。

<button onClick="alert('hello');">Click me</button>

0

,如果你想在你的HTML文件

<script> 
 
     function hello(){ 
 
    \t alert('hello') 
 
     } 
 
    </script> 
 

 
    <button id="bait" onClick="hello()"> 
 
     Click me 
 
    </button> 
 
    <!-- OR --> 
 
    <!-- <button onclick="javascript:(() => {alert('hello')})()"> --> 
 
    <!-- But it's good for short function only -->

所有這一切都可以做這樣的事情,但我認爲你應該使用jQuery,而不是(如果你能)



如果你想這樣做,只需添加一個clickHandler事件功能:

$("#bait").on("click",() => { 
 
     alert('hello') 
 
    })
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> 
 

 
<button id="bait">Click me </button>

有點大材小用了提示,但我想你問這個了一個更爲複雜的功能,所以它會更容易整體imo