創建多個按鈕時,如何獲取按鈕的值?目前在我的 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));
}
uj5u.com熱心網友回復:
如果要添加這么多按鈕,請使用事件委托。向父容器添加一個偵聽器,添加按鈕,然后在偵聽器函式中檢查單擊的元素是否為按鈕,并記錄其值。
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>
uj5u.com熱心網友回復:
以下代碼將在單擊時將按鈕的值記錄到控制臺。
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));
}
uj5u.com熱心網友回復:
嘗試使用資料屬性。它們使您的代碼更易于閱讀,并提供了一種在元素內部傳遞資料的好方法 - 您可以使用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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387139.html
標籤:javascript 按钮
