JS中matches()方法与相等运算符的区别及代码问题解析
问题:下拉菜单点击判断中matches方法为何不生效?
我在编写下拉菜单外部点击关闭的代码时,想用条件判断点击事件目标的id是否与下拉按钮的id一致(并非所有点击都要触发菜单关闭),但发现两段近似的条件语句在原生JS中表现不同:
第一段代码(正常输出"ok"):
// Close the dropdown menu if the user clicks outside of it window.onclick = function(event){ if (event.target.id == dropDownBtn.id){ console.log("ok"); // console output: ok } }
第二段代码(无输出):
// Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { if (event.target.matches(dropDownBtn.id)){ console.log("ok"); // console output: } }
我几乎没有JS开发经验,想了解为何第一段代码正常运行,第二段却没有输出。
解答
两段代码的核心差异在于**matches()方法的参数要求**:
第一段代码逻辑很直接:
event.target.id获取的是点击目标元素的id字符串,dropDownBtn.id是下拉按钮的id字符串,两者直接做字符串相等比较,匹配时就会触发输出,逻辑没问题。第二段代码的问题出在
matches()的用法上:matches()方法接收的参数必须是合法的CSS选择器字符串,而不是单纯的id值。比如你的按钮id是myDropdownBtn,那正确的CSS选择器应该是#myDropdownBtn(带#前缀表示匹配id)。你现在直接传入dropDownBtn.id(也就是不带#的id字符串),matches()会把它当成标签名去匹配(比如找<myDropdownBtn>标签),自然找不到对应的元素,所以条件不成立,没有输出。
修正后的第二段代码应该这样写:
// Close the dropdown menu if the user clicks outside of it window.onclick = function(event) { // 用模板字符串拼接出正确的CSS id选择器 if (event.target.matches(`#${dropDownBtn.id}`)){ console.log("ok"); // 现在会正常输出ok } }
内容的提问来源于stack exchange,提问作者bkh6722
相关产品推荐
相关产品推荐

