使用 .innerHTML 成功添加了按钮,但无法使用其类名访问按钮


function displaMatches (matches) {
var searchText = document.querySelector('.search').value;
var menu = document.querySelector('.menu')
matches.forEach(match => {
menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`
});
var suggestions = document.querySelectorAll('.suggestion');
suggestions.forEach(suggestion => {
suggestion.addEventListener('click', () => {
document.querySelector('.search').value = suggestion.textContent;
});
});
}
var search = document.querySelector('.search')
search.addEventListener('change', () => {
var searchText = document.querySelector('.search').value
autocomplete();
});
search.addEventListener('keyup', () => {
var searchText = document.querySelector('.search').value
autocomplete();
});
function autocomplete () {
var searchText = document.querySelector('.search').value
fetch(`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/autocomplete?&text=${searchText}&latitude=37.3351534&longitude=-122.0352478`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${access_token}`,
}
}).then((res) => {
return res.json();
}).then((data) => {
var allData = [];
allData.push(data);
console.log(allData);
let businesses = allData[0].businesses
let categories = allData[0].categories
let terms = allData[0].terms
let matches = [];
businesses.forEach(business => {
matches.push(business.name);
});
categories.forEach(category => {
matches.push(category.title);
});
terms.forEach(term => {
matches.push(term.text);
});
displaMatches(matches);
});
}

我可以在页面上看到按钮被成功添加到菜单中。然而,当我尝试使用类名"recommendation"访问一个按钮时,我得到的是null。我做错了什么?

我更改了代码,displayMatches函数现在工作正常。然而,在我将建议添加到搜索框后,搜索按钮就不再工作了。如果我禁用了建议功能,并在搜索框中键入我自己的单词,我可以搜索任何没有问题的内容。有人能解释一下原因吗?

希望这能有所帮助。我重写了函数

function displaMatches (matches) {
	var menu = document.querySelector('.menu')
	matches.forEach(match => {
		//Create/add objects in javascript
		$li = document.createElement('li');
	  	$btn = document.createElement('button');
	  	$btn.className = 'suggestion';
	  	$btn.append(match);
	  	$li.appendChild($btn)
	  	menu.appendChild($li);
	});
	var suggestion = document.querySelectorAll('.suggestion')//this should return array of buttons with the defined classname
	console.log('ppp', suggestion[0]);
	suggestion.forEach(match => {
		match.onclick = () => {
			console.log(match.textContent)
			searchText = match.textContent;
		};
	})
}

您似乎缺少一个=符号。应该是:

menu.innerHTML += `<li><button class="suggestion">${match}</button></li>`

此外,请记住,如果要在每个.suggestion中添加一个事件侦听器,而不是仅添加第一个,则需要使用var suggestion = document.querySelectorAll('.suggestion')

有很多错误,但这里有一些有效的方法。对不起,穿着旧的普通睡衣。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul class="menu">
</ul>
<div id="searchtext">
</div>
<script>
function displaMatches (matches) {
var menu = document.querySelector('.menu');
var item = function(match) {
return '<li><button class="suggestion">' + match + '</button></li>';
};
var menuItems = [];
for(var i=0;i<matches.length;i++){
var m = matches[i];
menuItems.push(item(m));
}
menu.innerHTML = menuItems.join('');
}

window.onload =  function() {
var matches = [ 'red', 'blue', 'red' ];
displaMatches(matches);
setTimeout(function() {
var suggestions = document.querySelectorAll('.suggestion');
for (var i = 0; i < suggestions.length; i++) {
suggestions[i].onclick = function () {
document.getElementById('searchtext').innerText += this.innerText;
};
}
}, 1000);
};
</script>
</body>
</html>

最新更新