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

时间:2017-11-15 19:31:48

标签: javascript html dom

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

我可以看到按钮被成功添加到页面上的菜单中。但是,当我尝试使用类名“suggestion”访问按钮时,我得到的是null。我做错了什么?

我更改了代码,displayMatches功能现在正常工作。但是,在我将建议添加到搜索框后,搜索按钮不再有效。如果我禁用了建议功能,并在搜索框中输入我自己的单词,我可以搜索任何没有问题的东西。任何人都可以解释原因吗?

3 个答案:

答案 0 :(得分:0)

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

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

另外,请注意,如果您要向每个 .suggestion添加一个事件监听器,而不仅仅是第一个,那么您需要使用var suggestion = document.querySelectorAll('.suggestion')

答案 1 :(得分:0)

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

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

}

答案 2 :(得分:0)

有很多错误,但这里有一些有用的东西。对不起,在旧的平原js。

   <!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>