gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:50:38 25 4
gpt4 key购买 nike

我有一些图像具有 data- 属性,例如:

    <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 属性选择器中?提前致谢...

最佳答案

当您使用 attribute selectors 时像 [attr = value],

Attribute values must be CSS identifiers or strings.

您没有引用该值,因此它被解析为 identifier .然而,

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

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

  • 转义值,例如如果 y123 你需要 \31 23

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

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

关于javascript - 在带有 data-id 属性的选择器中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39596996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com