簡體   English   中英

如何使用處理程序將參數傳遞給 function?

[英]How can I pass an argument into a function with a handler?

這是我的新代碼...

<html>
<div class='header'>
    <a href='ks3-science.php' id='science'>KS3 Science</a>
</div>;

</html>

<script>
    varhandlers = {
        getHandler: function (str) {
            return this[str];
        },
        '#science': function () {
            $.get('load-topic.php', {
                topic: "Animal and Plant Cells"
            });
        },
    };

    $('#science').on('click', handlers.getHandler('#science'));
</script>

我的舊代碼是這樣的......

<html>
<div class='header'>
    <a href='ks3-science.php' id='science'>KS3 Science</a>
</div>;

</html>

<script>
    $('#science').on('click', function () {
        $.get('load-topic.php', {
            topic: "Animal and Plant Cells"
        });
    );
</script>

我只是不確定處理程序是如何工作的,所以我不知道如何使用處理程序將參數傳遞給 function。

您可以將參數附加到具有data屬性的特定 html,並在單擊處理程序中單擊元素時檢索數據。

 let display = $('#display'); $('.demo').click(function(){ let data = $(this).data('name'); display.html(data); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="display"> Click the follwing </div> <ul> <li class="demo" data-name="data1"> data 1 </li> <li class="demo" data-name="data2"> data 2 </li> </ul>

為了使用您的處理程序,您需要將處理程序 function 包裝在回調中,如下所示。

$('#science').on('click', function() {
     var id = $(this).attr('id'); // assume the argument you want to pass is id
     handlers.getHandler(id);
});
var handlers = {
  getHandler: function (str) {
    return this[str]('what ever argument you want');
  },
  '#science': function (argument) {
    $.get('load-topic.php', {topic: "Animal and Plant Cells"});
  },
};

$('#science').on('click',()=>{ handlers.getHandler('#science')});

您不能像調用普通函數那樣調用傳遞給事件處理程序的函數。 因此,例如,您不能這樣做:

const myFunc = (myArg) => {
   console.log(myArg);
}

$('#science').on('click', myFunc);

myFunc("Testing...");

並期望它在事件觸發時打印出Testing... 相反,你會得到完全不同的東西。 這是因為這些函數采用默認參數 - 例如event參數。

如果您想從事件處理程序內部使用自定義參數調用 function,您應該在回調 function 內部執行此操作。 這是一個例子:

const myFunc = (myArg) => {
   console.log(myArg);
}

$('#science').on('click', function() {
    myFunc("Testing...");
});

現在,當用戶單擊元素時, console.log將按預期打印出Testing...

暫無
暫無

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

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