jQuery 返回选定选项属性值

发布于 2024-12-21 17:08:18 字数 418 浏览 3 评论 0原文

如果我有 html,

<select id="autoplay">
    <option data-autoplay="">no</option>
    <option data-autoplay="1">yes</option>
</select>

如何使用 jQuery 返回与所选选项相关的 data-autoplay 值并将其设置为变量 var autoplay = *selected value*

因此,如果我选择 no,它不会返回任何内容,如果我选择 yes,它会返回 1,因此 var autoplay = "1";

if I have the html

<select id="autoplay">
    <option data-autoplay="">no</option>
    <option data-autoplay="1">yes</option>
</select>

how using jQuery can I return the data-autoplay value in respect to which option is selected and set it as a variable var autoplay = *selected value*

so if I select no it returns nothing and if I select yes it returns 1 so var autoplay = "1";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抚笙 2024-12-28 17:08:18

尝试以下代码,

$("#autoplay option:selected").attr("data-autoplay");

或者

$("#autoplay option:selected").data("autoplay");

try following code,

$("#autoplay option:selected").attr("data-autoplay");

or

$("#autoplay option:selected").data("autoplay");
最好是你 2024-12-28 17:08:18

您可以使用 attr() 方法获取属性的值:

var autopplay =  $('#autoplay option:selected').attr('data-autoplay');

if (!autoplay || autoplay == '') {
    // an empty string was returned
}
else if (autoplay == 1) {
    /* remember not to trust your users, so validate in/on the server
       if you're storing the variable/result...
    // 1 was returned
}

也可以使用 data('autoplay'),它将查看 data -前缀属性带有与data-后面的选择器(自动播放)匹配的字符串,因此在这种情况下它将查找:data-autoplay(有点明显, 我想)。

参考文献:

You can use the attr() method to get the value of an attribute:

var autopplay =  $('#autoplay option:selected').attr('data-autoplay');

if (!autoplay || autoplay == '') {
    // an empty string was returned
}
else if (autoplay == 1) {
    /* remember not to trust your users, so validate in/on the server
       if you're storing the variable/result...
    // 1 was returned
}

It's possible to also use data('autoplay'), which will look at data- prefixed attributes with a string matching the selector (autoplay) following the data-, so in this case it would look for: data-autoplay (somewhat obviously, I suppose).

References:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文