[英]Standard way of getting textContent of clicked dropdown element not working
I have a simple dropdown list and cant seem to get the textContent of the clicked element.我有一个简单的下拉列表,似乎无法获得单击元素的 textContent。 Should be fairly simple but apparently one can make a science out of it.应该相当简单,但显然可以从中得出一门科学。 So any help would be appreciated.所以任何帮助将不胜感激。
document.querySelector('#myDropdown').addEventListener('click', function() { console.log(this.textContent); var er = document.querySelector("#myDropdown"); var result = er.value; console.log(result); var e = document.getElementById("myDropdown"); var text = e.options[e.selectedIndex].text; console.log(text); })
<div class="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <div class="dropdown"> <button class="dropbtn">Dropdown <i class="fa fa-caret-down"></i> </button> <div id="myDropdown" class="dropdown-content"> <a>Link 1</a> <a>Link 2</a> <a>Link 3</a> </div> </div> </div>
The first consolelog logs all elements of the dropdown list, the second "undefined" and the third says "Uncaught TypeError".第一个控制台日志记录下拉列表的所有元素,第二个“未定义”,第三个显示“未捕获的类型错误”。 Is it because my dropdown is not made with the traditional select/ options style ?是不是因为我的下拉菜单不是用传统的选择/选项样式制作的? Thanks and nice Sunday.谢谢和愉快的星期天。
Inside an event listener which is a function
, this
inside it will refer to the element the listener was attached to.在作为function
的事件侦听器内部, this
内部将引用侦听器附加到的元素。 Here, that's the #myDropdown
<div>
.在这里,这是#myDropdown
<div>
。
The e.options[e.selectedIndex]
method only works for <select>
s. e.options[e.selectedIndex]
方法仅适用于<select>
s。
If you want to identify which link was clicked, first make sure the event.target
(the clicked element) is an <a>
, then extract the event.target
's textContent
:如果你想确定哪个链接被点击,首先确保event.target
(被点击的元素)是一个<a>
,然后提取event.target
的textContent
:
document.querySelector('#myDropdown').addEventListener('click', function(event) { if (event.target.matches('a')) { console.log(event.target.textContent); } })
<div class="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <div class="dropdown"> <button class="dropbtn">Dropdown <i class="fa fa-caret-down"></i> </button> <div id="myDropdown" class="dropdown-content"> <a>Link 1</a> <a>Link 2</a> <a>Link 3</a> </div> </div> </div>
You do need to check if the clicked element is an <a>
first - otherwise, clicks on the #myDropdown
but not on an inner <a>
will result in logs too, which you don't want.您确实需要先检查被点击的元素是否是<a>
- 否则,点击#myDropdown
而不是内部<a>
也会导致日志,这是您不想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.