如何用JS获取按钮的值

How to get value of button with JS

创建多个按钮时,如何获取按钮的值?目前在我的 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));
}

点击按钮时,以下代码会将按钮的值记录到控制台。

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));
}

尝试使用 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>

如果要添加这么多按钮,请使用 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>