[英]How write function in onclick button attribut
我試圖直接在我的按鈕的屬性onclick中使用一個函數,但我總是一個錯誤。 例:
<button onclick="function() { alert('hello'); }">Click me</button>
結果是:
未捕獲的SyntaxError:意外的令牌(
無需使其成為函數,只需列出語句:
<button onclick="alert('hello');alert('hello 2');alert('hello 3');">Click me</button>
下面的代碼將允許您在onclick屬性中添加功能。
點擊我
<button onclick="javascript:(function() { alert('hello'); })()">Click me</button>
你應該寫這樣的代碼。
<button onClick="alert('hello');">Click me</button>
如果你想在你的html文件中使用所有這些,你可以做這樣的事情
<script> function hello(){ 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會更容易
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.