繁体   English   中英

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

[英]Using a variable in selector with the data-id attribute

我有一些图像具有如下数据属性:

    <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 + '"]') 

暂无
暂无

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

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