简体   繁体   中英

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. 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? Thanks in advance...

When you use a attribute selectors like [attr = value] ,

Attribute values must be CSS identifiers or strings .

You didn't quote the value, so it's parsed as an identifier . However,

In CSS, identifiers [...] cannot start with a digit

Therefore, your numerical selector is invalid. You can:

  • Escape the value, eg if y is 123 you need \\31 23

     document.querySelector('[data-picture =' + CSS.escape(y) + ']') 
  • Use strings, eg if you know y does not contain quotes,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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