简体   繁体   English

Wordpress 使用 javascript 更改 iframe src

[英]Wordpress using javascript to change iframe src

I am trying to implement javascript on a Wordpress page which uses a template php file.我正在尝试在使用模板 php 文件的 Wordpress 页面上实现 javascript。 But the onlcick is not changing the src and in the browser debug console I am receiving the message "Uncaught Type Error: Cannot set property 'src' of null"但是 onlcick 没有更改 src 并且在浏览器调试控制台中我收到消息“未捕获类型错误:无法设置属性 'src' of null”

I have added the Javascript code below to a.js file我已将下面的 Javascript 代码添加到 a.js 文件中

videoFrame = document.getElementById('video');
function setLanguage(lang) {
  switch(lang) {
    case 'en':
      videoFrame.src = 'https://player.vimeo.com/video/1';
      break;
    case 'fr':
      videoFrame.src = 'https://player.vimeo.com/video/2';
      break;
  } 
}

I then added the enqueue to the functions.php file然后我将队列添加到 functions.php 文件中

add_action('wp_enqueue_scripts' ,'translate_script');
function translate_script(){wp_enqueue_script('translate', get_stylesheet_directory_uri().'/js/translate.js');}

Finally I added the code for the buttons on the template.php file最后,我在 template.php 文件中添加了按钮的代码

<button onclick="setLanguage('en')"></button>
<button onclick="setLanguage('fr')"></button>

Any help or suggestions would be appreciated as I can get the code working in CodePen but not within the wordpress environment.任何帮助或建议将不胜感激,因为我可以让代码在 CodePen 中工作,但不能在 wordpress 环境中工作。 Thanks谢谢

The problem is that you are trying to get the videoFrame before the full page is loaded.问题是您试图在加载整个页面之前获取videoFrame You can fix this problem by putting that code inside a document.ready or by acessing the video inside the function, so it search for it when the button is clicked (and the full website has been already loaded)您可以通过将该代码放入 document.ready 或通过访问 function 中的视频来解决此问题,以便在单击按钮时搜索它(并且已经加载了完整的网站)

function setLanguage(lang) {
  videoFrame = document.getElementById('video');
  switch(lang) {
    case 'en':
      videoFrame.src = 'https://player.vimeo.com/video/1';
      break;
    case 'fr':
      videoFrame.src = 'https://player.vimeo.com/video/2';
      break;
  } 
}

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

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