简体   繁体   English

Javascript 按钮切换在第一次点击时不起作用,只有第二次点击或更多

[英]Javascript button toggle not working on first click, only second click or more

I'm not sure what's going on here, but I have this javascript toggle button on the top left of my video that I'm using to swap the video embed source and to change the closed captioning text of the toggle from "cc on" to "cc off" and back... but it only works after an initial click.我不确定这里发生了什么,但我的视频左上角有这个 javascript 切换按钮,我用它来交换视频嵌入源并将切换的隐藏式字幕文本从“cc on”更改到“cc off”并返回......但它仅在初始点击后才有效。 What am I missing here?我在这里想念什么?

Console shows a "Button not defined" on page load, but I'm not sure what isn't right.控制台在页面加载时显示“未定义按钮”,但我不确定哪里不对。

HTML: HTML:

<div class="navbar">
  <button id="togglecc" value="OFF" onclick="toggle(this);">cc on</button>
</div>
<div id="player">
  <div id="la1-video-player" data-embed-id="87e859b2-5db8-4ad8-bac7-575c22288930"></div>
  <script type="application/javascript" src="https://control.livingasone.com/webplayer/loader.min.js"></script>
</div>

Script:脚本:

function toggle(button) {
  v = document.getElementById("togglecc");
  vp = document.getElementById("player");
  if (v.value == "ON") {
    v.value = "OFF";
    v.innerHTML = 'cc off';
    vp.innerHTML = '<div id="la1-video-player" data-embed-id="9257a531-25ce-48bd-821b-9335681c45d8"></'+'div>';var a=document.createElement("script");a.setAttribute("src","//control.livingasone.com/webplayer/loader.min.js");document.getElementById('player').appendChild(a);
  } else {
    v.value = "ON";
    v.innerHTML = 'cc on';
    vp.innerHTML = '<div id="la1-video-player" data-embed-id="87e859b2-5db8-4ad8-bac7-575c22288930"></'+'div>';var a=document.createElement("script");a.setAttribute("src","//control.livingasone.com/webplayer/loader.min.js");document.getElementById('player').appendChild(a);
  }
}

https://jsfiddle.net/milkboy31/tg02Lv4c/ https://jsfiddle.net/milkboy31/tg02Lv4c/

Here is your updated fiddle这是你更新的小提琴

toggle button切换按钮

Also you should avoid calling function on button element like this此外,您应该避免在这样的按钮元素上调用 function

onclick="toggle(this);"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM