簡體   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