簡體   English   中英

如何在 JavaScript 中放置在事件處理程序中的函數中獲取 this.value 作為參數?

[英]How to get this.value as an argument in a function placed in an event handler in JavaScript?

 function change_myselect(sel) { return new sel; } function customers () { var xmlhttp, myObj, i, tbl = ''; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); tbl += '<table border="1">'; for (i in myObj) { tbl += '<tr><td>' + myObj[i] + '</td></tr>' ; } tbl += '</table>'; document.getElementById('showSelection').innerHTML = tbl; } }; xmlhttp.open('GET', 'suppliers.txt', true); xmlhttp.send(); }
 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h2>Make a table based on the value of a drop down menu.</h2> <select onchange="change_myselect(customers)"> <option value="">Choose an option</option> <option value="customers">Customers</option> <option value="products">Products</option> <option value="suppliers">Suppliers</option> </select> <p id="showSelection"></p>
在上面的代碼中,它起作用是因為我在 change_myselect 函數中手動編寫了 CUSTOMERS 作為參數。

 function change_myselect(sel) { return new sel; } function customers () { var xmlhttp, myObj, i, tbl = ''; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); tbl += '<table border="1">'; for (i in myObj) { tbl += '<tr><td>' + myObj[i] + '</td></tr>' ; } tbl += '</table>'; document.getElementById('showSelection').innerHTML = tbl; } }; xmlhttp.open('GET', 'customers.txt', true); xmlhttp.send(); }
 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h2>Make a table based on the value of a drop down menu.</h2> <select onchange="change_myselect(this.value)"> <option value="">Choose an option</option> <option value="customers">Customers</option> <option value="products">Products</option> <option value="suppliers">Suppliers</option> </select> <p id="showSelection"></p>

我想根據下拉菜單的值制作一個表格。 我使用 ONCHANGE 事件處理程序來獲取選項的值並將其傳遞給 change_myselect 函數,以使用 JSON 從服務器檢索相應的信息。 當我寫 CUSTOMERS 函數的名稱時,在 change_myselect 函數中它工作正常。 但是當我使用 THIS.VALUE 時,它不起作用。 我已經使用 NEW 關鍵字返回並調用 CUSTOMERS 函數而不使用括號。

你從 HTML 中得到的一切都是字符串。 當您將字面書寫的customers傳遞給change_myselect函數時,它是對customers函數的引用。 當您傳遞this.value ,它只是一個字符串。 這就是為什么您會收到錯誤而不是函數調用的原因。

根據您的代碼,您似乎想要調用一個與所選選項的值同名的函數。 在 JavaScript 中,字符串不能直接轉換為引用(以合理的方式),這正是您在引用函數時所需要的。 您需要一個輔助對象來獲取引用。

 // Helper object contains methods calling the functions const handlers = { customers () {customers();}, products () {products();}, suppliers () {suppliers();} } function change_myselect(sel) { // Check, if the passed property name is a function in handlers object if (typeof handlers[sel] === 'function') { // A method named as the passed string was found // Call the found method handlers[sel](); } } function customers () { console.log('customers called'); } function products () { console.log('products called'); } function suppliers () { console.log('suppliers called'); }
 <h2>Make a table based on the value of a drop down menu.</h2> <select onchange="change_myselect(this.value)"> <option value="">Choose an option</option> <option value="customers">Customers</option> <option value="products">Products</option> <option value="suppliers">Suppliers</option> </select> <p id="showSelection"></p>

change_myselect ,代碼檢查輔助對象是否包含與傳遞的字符串同名的方法。 為此,我們使用括號表示法,其中括號中的字符串被評估為括號之前對象的屬性。 如果找到傳遞的屬性,代碼將再次使用括號表示法調用handlers對象中的方法。 注意行尾的括號。 輔助方法然后調用實際的函數來完成這項工作。

如果您只有要調用的customer函數,則只需將引用其他函數的方法從輔助對象中刪除即可。 您還可以通過將函數的代碼直接放在handlers對象的方法中來簡化代碼。

上面代碼的問題似乎是您所指的

this.value

您可以重新訪問您的change_myselect函數以將event作為參數,然后從事件中提取選定的值,例如:

var change_myselect = function(event) {
  var selectedValue = event && event.target && event.target.value || '';
  return selectedValue || '';
};

確保您還修改了代碼的 HTML 部分以將事件作為參數傳遞:

<select onchange="change_myselect(event)">

您也可以將change_myselect輸出存儲在另一個變量中,以便在您的 http 請求邏輯中使用。

您實際上不會在任何地方使用您的選擇值或執行任何 xhr 請求。 嘗試將您的 js 代碼更改為如下所示:

 function performXhr(entity) {
      var xmlhttp,
        myObj,
        i,
        tbl = "";

      xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          myObj = JSON.parse(this.responseText);
          tbl += '<table border="1">';
          for (i in myObj) {
            tbl += "<tr><td>" + myObj[i] + "</td></tr>";
          }
          tbl += "</table>";
          document.getElementById("showSelection").innerHTML = tbl;
        }
      };

      xmlhttp.open("GET", `${entity}.txt`, true);
      xmlhttp.send();
    }

和你的 HTML 標記

    <select onchange="performXhr(this.value)">
      <option value="">Choose an option</option>
      <option value="customers">Customers</option>
      <option value="products">Products</option>
      <option value="suppliers">Suppliers</option>
    </select>

暫無
暫無

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

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