[英]Using a variable in selector with the data-id attribute
I have some images that have a data- attribute like: 我有一些图像具有如下数据属性:
<img id="popup" class="Absolute_Center is_Image" alt="Girl Popup" data-picture="">
<img src="https://s3-us-west-2.amazonaws.com/example.jpg" data-picture = "1">
<img src="https://s3-us-west-2.amazonaws.com/example2.jpg" data-picture = "2">
etc...
I want to add an event listener to retrieve the next picture in the series. 我想添加一个事件监听器来检索系列中的下一张图片。 I figured I can do this: 我想我可以这样做:
var oimgPopup = document.getElementById("popup");
/* retrieve data-picture value of current image showing in the image popup */
var y = oimgPopup.dataset.picture;
var y = oimgPopup.dataset.picture;
y = y + 1;
// Prints out corect data-picture value + 1
var nextImage = document.querySelector('[data-picture =' + y + ']');
console.log(nextImage);
/* SyntaxError: An invalid or illegal string was specified
var nextImage = document.querySelector('[data-picture =' + y + ']'); */
where I will retrieve the next image element object in the series and then I will insert it into #mypopup image element. 我将在其中检索系列中的下一个图像元素对象,然后我将其插入到#mypopup图像元素中。 However I am getting an illegal string message when I run this. 但是当我运行它时,我收到一个非法的字符串消息。 Does anyone know how to incorporate a variable into the querySelector attribute selector? 有谁知道如何将变量合并到querySelector属性选择器中? Thanks in advance... 提前致谢...
When you use a attribute selectors like [attr = value]
, 当您使用[attr = value]
等属性选择器时 ,
Attribute values must be CSS identifiers or strings . 属性值必须是CSS 标识符或字符串 。
You didn't quote the value, so it's parsed as an identifier . 您没有引用该值,因此将其解析为标识符 。 However, 然而,
In CSS, identifiers [...] cannot start with a digit 在CSS中,标识符[...]不能以数字开头
Therefore, your numerical selector is invalid. 因此,您的数字选择器无效。 You can: 您可以:
Escape the value, eg if y
is 123
you need \\31 23
逃避该值,例如,如果y
为123
,则需要\\31 23
document.querySelector('[data-picture =' + CSS.escape(y) + ']')
Use strings, eg if you know y
does not contain quotes, 使用字符串,例如,如果你知道y
不包含引号,
document.querySelector('[data-picture = "' + y + '"]')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.