簡體   English   中英

如何通過單擊按鈕運行 JS 腳本?

[英]How to run a JS script by clicking on a button?

我正在嘗試在我的網站上實現代碼示例的演示。 https://yuricoder.dev/docs/nunjucks/templates/code-example/code-example-test.html

我想讓示例中的代碼在您單擊按鈕時運行。

最明顯的方法是在 function 中放一個示例並使用 'onclick' 調用,但這並不合適,因為代碼示例本身可能包含函數。

在下面的代碼中,我在另一個 function 中得到了一個 function,因此腳本無法運行。

 <button title="Run" onclick="example1()"></button> <script> function example1() { // javascript (example-1) function compareNumeric(a, b) { if (a > b) return 1; if (a == b) return 0; if (a < b) return -1; } let arr = [ 1, 2, 15 ]; arr.sort(compareNumeric); alert(arr); // 1, 2, 15 } </script>

我想在這個站點上實現https://javascript.info/bind它使用屬性 data-action="run"。 但我不知道如何將它鏈接到我的示例。

像這樣的東西:

<button id="fooBtn">X</button>

JavaScript:

function applyBindings() {
    document.getElementById("fooBtn").addEventListener("click", compareNumeric);
}

applyBindings();


function compareNumeric(a, b) {
    if (a > b) return 1;
    if (a == b) return 0;
    if (a < b) return -1;
}

let arr = [ 1, 2, 15 ];
arr.sort(compareNumeric);
alert(arr);  // 1, 2, 15

您可以像您正在做的那樣包裝您的 function 並在里面添加另一個立即執行的 function :

<button title="Run" onclick="example1()"></button>
function example1() {

  (function() {
    alert('I run when example1 runs!')
  })();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM