简体   繁体   English

用香草JS努力绑定和匹配DOM元素

[英]Struggling to bind and match DOM elements with vanilla JS

I prefer to bind all my DOM elements at the top of my code so that the ID or class reference is only hard coded once, even though the element is used multiple times within the code. 我更喜欢将所有DOM元素绑定在代码的顶部,以便ID或类引用仅被硬编码一次,即使该元素在代码中已多次使用。 Something like this: 像这样:

var startButton = "#startButton";
var closeButtons = ".button.close";

That works well with selectors, such as document.querySelector. 这与选择器(例如document.querySelector)一起很好地工作。 The challenge occurs when I'm about to compare an element ID to one of the static variables above, like for instance during a click event: 当我要将元素ID与上面的静态变量之一进行比较时(例如在click事件期间),就会发生挑战:

e.target.id == startButton

Since the variable startButton contains a sharp, I would have to do something like this: 由于变量startButton包含尖锐字符,因此我必须执行以下操作:

e.target.id == startButton.replace('#', '')

This is obviously not the ideal way of handling things, so I'm wondering if there's a better way to bind DOM elements for later use? 这显然不是处理事物的理想方法,所以我想知道是否有更好的方法来绑定DOM元素以供以后使用?

Please note that I did consider retrieving the elements using a selector right away, like document.querySelector, but that prevents me from manipulating the elements later on. 请注意,我确实考虑过立即使用选择器来检索元素,例如document.querySelector,但这使我以后无法操纵这些元素。

EDIT: My note above turns out to be wrong. 编辑:我上面的笔记原来是错误的。 It's totally possible to manipulate the elements later on. 以后完全有可能操纵这些元素。 So the question is whether it's better to store selectors in variables, or to store nodes in variables. 因此,问题是将选择器存储在变量中还是将节点存储在变量中是更好的选择。 As pointed out below, the DOM element might not exist while it's being declared, so it might be better to store the selector in a variable, like I'm doing above. 如下所述,DOM元素在声明时可能不存在,因此最好将选择器存储在变量中,就像我上面所做的那样。

For the specific example in your question, you can use .matches() : 对于您问题中的特定示例,可以使用.matches()

if (e.target.matches(startButton))

The .matches() DOM API takes a selector as its argument. .matches() DOM API以选择器作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM