簡體   English   中英

為多個 id 創建 onclick 事件

[英]create onclick event for multiple ids

我寫了一個js函數:

$(document).on('click', '#id1', function () {
$.ajax({
  type: "POST",
  url: "/url",
  data: { uInput: 'id1' },
  success: function (response) {
    some code....
  },
  error: function (error) {
    console.log(error);
  }
});
});

問題是,由於我有更多具有各種 ID 的可點擊對象,我想創建一個腳本/函數,它不僅可以接受來自 #id1 的 onclick 事件,還可以接受來自 #id2、#id3 等的 onclick 事件......

我嘗試了以下建議: https ://stackoverflow.com/a/18508894/11271927 和這里https://stackoverflow.com/a/18508907/11271927但每當我編輯代碼以適應我的代碼結構時,它不會工作。

var options = {
    id1: 'id1',
    id2: 'id2',
    id3: 'id3',
    id4: 'id4'
  };
  $('.options').click(function () {
    $.ajax({
      type: "POST",
      url: "/url",
      data: options[this.id],
      success: function (response) {
        some code....
      },
      error: function (error) {
        console.log(error);
      }
    });
  });

本質上,此代碼在點擊時不會做任何事情。

如果您知道我錯過了什么或做錯了什么,請提供幫助。

如果您想擁有一個函數,該函數將在多個元素(例如按類)上具有單擊偵聽器,您可以像這樣嘗試:

<button class="button" id="id1">A</button>
<button class="button" id="id2">B</button>
<button class="button" id="id3">C</button>

<script>
    $(document).on('click', '.button', function () {
        $.ajax({
            type: "POST",
            url: "/url",
            data: {
                uInput: this.getAttribute('id'),
            },
            success: function (response) {
                console.log(response);
            },
            error: function (error) {
                console.log(error);
            }
        });
    });
</script>

您可以在文檔上設置click事件偵聽器,並在其函數內使用條件將相同的語句塊應用於任何元素組。

例如,您可以過濾 id 以字符串“id”開頭的目標,如下所示(核心 js):

document.addEventListener('click', event => {

  if (event.target.id.indexOf('id') == 0) {
     // commands to apply to those elements;
  } // end if #id* click;

// any number of other groups or individual elements can be added, each with a conditional to filter the required ones.

}); // end event listener

如果您需要更多特異性,請細化條件,例如(在文檔事件偵聽器函數內部):

const id=event.target.id;
if (id == "id1" || id == "id3" || id == "somethingElse") {
// relevant statements;
};

我通常默認使用文檔事件偵聽器,沒有額外的計算成本,而且我發現單個事件偵聽器更易於維護。

暫無
暫無

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

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