简体   繁体   中英

I have a list of buttons with the same class name but different inner text, how do I get the value of the text on click?

My list is being populated with this block of code:

function addToHistory(cityName) {
  let searchHistory = JSON.parse(localStorage.getItem("Weather Search History")) || [];
  searchHistory.push(cityName);
  localStorage.setItem("Weather Search History", JSON.stringify(searchHistory));
};
function updateHistory() {
  let searchHistory = JSON.parse(localStorage.getItem("Weather Search History")) || [];
  $("#searchHistory").html(searchHistory
    .map(searchHistoryList => {
      return (`<li><button class="btn btn-link"> ` + searchHistoryList + `</button></li>`);
    })
    .join(""));
};

and that works great. It pulls from an array in local storage that is created each time the user enters a search term. Then populates the site's sidebar with said list. However, I'm not sure how to then take the text values of the buttons out so that I may manipulate it.

Currently have:

$('#searchHistory').on('click', function () {
console.log($(???).val());
});

You want.text() or innerText (plain JavaScript). this refers to the current element. You can also use event.target.

$('#searchHistory').on('click', function () {
console.log($(this).text());
});

Try this in your function:

console.log($(this).innerHTML());

"this" refers to the specific element that triggered the click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM