使用具有data-id属性的选择器中的变量

Using a variable in selector with the data-id attribute

本文关键字:选择器 变量 属性 data-id      更新时间:2023-09-26

我有一些图像有一个数据属性,如:

    <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...

我想添加一个事件侦听器来检索系列中的下一张图片。我想我可以这样做:

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  + ']'); */

,我将检索下一个图像元素对象的系列,然后我将它插入到#mypopup图像元素。然而,当我运行这个时,我得到一个非法的字符串消息。有人知道如何将变量合并到querySelector属性选择器中吗?

当您使用像[attr = value]这样的属性选择器时,

属性值必须是CSS标识符或字符串。

您没有引用该值,因此它被解析为标识符。然而,

在CSS中,标识符[…不能以数字

开头

因此,您的数字选择器无效。您可以:

  • 转义值,例如,如果y123,则需要'31 23

    document.querySelector('[data-picture =' + CSS.escape(y) + ']')
    
  • 使用字符串,例如,如果您知道y不包含引号,

    document.querySelector('[data-picture = "' + y + '"]')