用按钮和jquery切换“data-property”

Toggle 'data-property' with a button & jquery

本文关键字:data-property 切换 jquery 按钮      更新时间:2023-09-26

我有一个全屏YouTube视频作为我正在开发的网站的背景,我正在尝试添加一个带有按钮的静音/取消静音切换。这就是我拉视频的方式:

<a id="bgndVideo" class="player" data-property="{videoURL:'https://youtu.be/KW2JUfgQct0',containment:'.video-section', quality:'high', autoPlay:true, mute:true, opacity:1}">bg</a>

我知道我想如何运行切换的逻辑,当按钮单击时,我希望数据属性更改,因此如果其数据属性为 mute:true onClick,我希望它更改为静音:false,然后在再次单击时返回。

这是我尝试过的——

$(document).ready(function(){
 $(".muteButton").click( function (){
    $(this).data('mute', !$(this).data('mute'));
});
});

带有锚标记 -

<a class="muteButton" href="#">Mute</a>

我已经查找了如何做到这一点但没有运气,我从未写过jquery,所以我迷路了,这是一件容易的事情吗?

谢谢

bgndVideo 的数据属性不是有效的 json 语法。 因此,它被视为字符串。

<a id='bgndVideo' class='player' data-property='{"videoURL":"https://youtu.be/KW2JUfgQct0" , "containment":".video-section", "quality":"high", "autoPlay":true, "mute":true, "opacity":1}'>bg</a> 
<a class="muteButton btn btn-default" href="#">Click me to Mute</a>
<div id="muteValueDiv"></div><br>
<div id="bgndVideoDataPropDiv"></div>
$(document).ready(function () {
      $(".muteButton").click(function () {
                $(bgndVideo).data('property').mute = !$(bgndVideo).data('property').mute;
                $('#muteValueDiv').html('After negation Mute Value is - ' + $(bgndVideo).data('property').mute);
                $('#bgndVideoDataPropDiv').html('After updating data property, data property is ' + JSON.stringify( $(bgndVideo).data('property')));
     });
});

请参考 jsfiddle: jsfiddle.net/u89oexea