【问题标题】:How to get value of button with JS如何使用 JS 获取按钮的值
【发布时间】:2022-01-19 23:18:18
【问题描述】:

当创建了多个按钮时,如何获取按钮的值?目前在我的 Javascript 文件中,我有它,因此我的搜索历史在列表中创建了一个按钮,其中包含标记的城市的“值”。

当我点击被制作的按钮时,我得到了未定义。

function recentSearch(city) {
    var addCity = document.createElement("button");
    addCity.setAttribute("value", city);
    addCity.textContent = city;
    document.getElementById("searchHistory").append(addCity);

    cities.push(city);
    localStorage.setItem("searches",JSON.stringify(cities));
}

【问题讨论】:

    标签: javascript button


    【解决方案1】:

    如果您要添加这么多按钮,请使用event delegation。向父容器添加一个侦听器,添加您的按钮,然后在侦听器函数中检查单击的元素是否为按钮,并记录其值。

    const searchHistory = document.querySelector('#searchHistory');
    
    // Add one listener to the container that calls `handleClick`
    searchHistory.addEventListener('click', handleClick, false);
    
    function handleClick(e) {
    
      // Destructure the nodeName and value from
      // the clicked element, and log the value if the
      // element is a button
      const { nodeName, value } = e.target;
      if (nodeName === 'BUTTON') {
        console.log(value);
      }
    }
    
    function recentSearch(city) {
      var addCity = document.createElement('button');
      addCity.value = city;
      addCity.textContent = city;
      searchHistory.append(addCity);
    }
    
    const cities = ['London', 'Rome', 'New York', 'Seoul', 'Kingston'];
    
    for (const city of cities) {
      recentSearch(city);
    }
    <div id="searchHistory"></div>

    【讨论】:

      【解决方案2】:

      以下代码将在单击时将按钮的值记录到控制台。

      function recentSearch(city) {
          var addCity = document.createElement("button");
          addCity.setAttribute("value", city);
          addCity.textContent = city;
          addCity.onclick = (e)=>{
              console.log(e.target.getAttribute('value'));
              //or whatever other code you want to do onclick
          }
          document.getElementById("searchHistory").append(addCity);
      
          cities.push(city);
          localStorage.setItem("searches",JSON.stringify(cities));
      }
      

      【讨论】:

        【解决方案3】:

        尝试使用data-attributes。它们使您的代码更易于阅读,并提供了一种在元素内部传递数据的好方法 - 您可以使用 element.dataset.<attribute_name> 访问它们的数据 - 在本例中为 e.target.dataset.value(从按钮单击侦听器中)。

        cities = []
        
        function recentSearch(city) {
          // FOR DEMO ONLY::
          if (!city) city = "city " + Math.ceil(Math.random() * 1000);
        
          var addCity = document.createElement("button");
          addCity.setAttribute("data-value", city);
          addCity.textContent = city;
          addCity.addEventListener('click', e => {
            console.log(`my city is: ${e.target.dataset.value}`);
          })
          document.getElementById("searchHistory").append(addCity);
          
        
          cities.push(city);
          // localStorage.setItem("searches",JSON.stringify(cities));
        }
        <div id='searchHistory'>
        </div>
        <button onclick='recentSearch()'>Make City</button>

        【讨论】:

        猜你喜欢
        • 2011-04-21
        • 2012-10-19
        • 2020-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多