Javascript document.querySelector 一个元素中的多个数据属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29937768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:21:20  来源:igfitidea点击:

document.querySelector multiple data-attributes in one element

javascriptjquerydomelement

提问by wiesson

I'm trying to find an element with document.querySelectorwhich has multiple data-attributes:

我试图找到一个document.querySelector具有多个数据属性的元素:

<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3" data-period="current">-</div>

I thought about something like this:

我想过这样的事情:

document.querySelector('[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"] [data-period="current"]')

But it does not work.
However, it works well, if I put the second data-attribute in a child-element like:

但它不起作用。
但是,如果我将第二个数据属性放在子元素中,则效果很好,例如:

<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"> <span data-period="current">-</span> </div>

So, is there an option to search for both attributes at once?
I've tried several options but I don't get it.

那么,是否可以选择同时搜索这两个属性
我尝试了几种选择,但我不明白。

回答by Arun P Johny

There should not be a space between the 2 selectors

2 个选择器之间不应有空格

document.querySelector('[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"][data-period="current"]')

if you give a space between them it will become a descendant selector, ie it will search for an element attribute data-period="current"which is inside an element with data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"like

如果你在它们之间留一个空格,它将成为一个后代选择器,即它会搜索一个元素data-period="current"内的元素属性,data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"例如

<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3">
    <div data-period="current">-</div>
</div>

回答by Milind Anantwar

space in selector looks for [data-period="current"]in[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"].You don't need to put space in between attribute value selector:

space in selector 查找[data-period="current"]in [data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"]。你不需要在属性值选择器之间放置空格:

document.querySelector('[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"][data-period="current"]')