2016-09-20 45 views
1

我有有一個像數據 - 屬性一些圖片:使用與數據-id選擇一個變量屬性

<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屬性選擇器中?在此先感謝...

+0

您忘記CL OSE自己的圖片廣告 – Neal

回答

3

當您使用attribute selectors[attr = value]

屬性值必須是CSS identifiersstrings

您沒有引用該值,因此它被解析爲identifier。然而,

在CSS中,標識符[...]不能以數字

因此,你的數字選擇是無效的開始。您可以:

  • 將數值例如如果y123你需要\31 23

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

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

當Y = Y + 1級聯不添加之後CONSOLE.LOG。我需要做一個Parseint(),添加到y,然後回到字符串y.toString()? – alan

+0

比我自己的答案要好得多。我完全忘記了'不能以數字開始'的限制。 –

+0

@alan我不喜歡'parseInt'。我會用'y = + y + 1'。它與字符串連接時已經被強制轉換爲字符串,所以'toString'不需要。 – Oriol