一行JS代码在Wordpress中被破坏了.不知道为什么

One line of JS code is breaking within Wordpress. Not sure why

本文关键字:坏了 不知道 为什么 JS 代码 Wordpress 一行      更新时间:2023-09-26
$(function(){
  $(".youtubeThumb").each(function(){
      $(this).bind('click touchstart', function(event){
        event.preventDefault();
      var ytLink = $(this).children('img').attr('src');
      //the line below is what keeps breaking
      var ytLink = ytLink.split('/vi/').pop().split('/').shift();
      var ytPlayList = 'PLDMZzXD-QCET2VK_l9aGhOXNMZjWjzI0g';
      $('.youtubeEmbed iframe').attr('src', '//www.youtube.com/embed/'+ytLink+'?list='+ytPlayList+'&wmode=transparent&autoplay=1');
    $('html, body').animate({
        scrollTop: $('.youtubeEmbed').offset().top
    }, 600);
      })
   })
});
//Error Below from console
Uncaught TypeError: Cannot read property 'split' of undefined ?page_id=28:169(anonymous function) ?       page_id=28:169n.event.dispatch jquery-2.1.1.min.js?ver=2.1.1:3r.handle

以前从未真正使用过wordpress,所以我可能会远离我正在尝试做的事情。指向该页面的链接 http://twistedmess.com/?page_id=28

正如您在单独的页面上看到的那样,代码可以正常工作 http://schottmandesign.com/test3

我尝试将脚本放在单独的 js 文件中,然后将其放入标题.php中,将其放入实际页面本身,现在它包含在一个短代码插件中,然后我在实际页面上调用该插件。任何帮助都非常感谢。

你想要的而不是孩子,是找到。 您希望以递归方式查看 jQuery 对象中的所有元素。 孩子只比父母深低一级。 有关玩具示例 http://jsfiddle.net/gq36et5x/1,请参阅此小提琴。

相反,您的代码应如下所示:

$(function(){
  $(".youtubeThumb").each(function(){
  $(this).bind('click touchstart', function(event){
    event.preventDefault();
  var ytLink = $(this).find('img').attr('src');
  //the line below is what keeps breaking
  var ytLink = ytLink.split('/vi/').pop().split('/').shift();
  var ytPlayList = 'PLDMZzXD-QCET2VK_l9aGhOXNMZjWjzI0g';
  $('.youtubeEmbed iframe').attr('src', '//www.youtube.com/embed/'+ytLink+'?list='+ytPlayList+'&wmode=transparent&autoplay=1');
  $('html, body').animate({
    scrollTop: $('.youtubeEmbed').offset().top
}, 600);
  })
  })
});

此外,没有必要运行 each 循环以绑定到 Click 事件。 你可以这样瘦身:

$(function(){
  $(".youtubeThumb").click(function(e){
    e.preventDefault();
    var ytLink, ytPlaylist; 
    ytPlaylist = 'PLDMZzXD-QCET2VK_l9aGhOXNMZjWjzI0g';
    ytLink = $(this).find('img').attr('src').split('/vi/').pop().split('/').shift();
    $('.youtubeEmbed iframe').attr('src', '//www.youtube.com/embed/'+ytLink+'?list='+ytPlayList+'&wmode=transparent&autoplay=1');
    $('html, body').animate({ scrollTop: $('.youtubeEmbed').offset().top}, 600);})
  })
});

img 标签不是 .youtubeThumb 元素的直接子元素,因此children更改为 find 。此外,find将返回一个元素数组(如果没有匹配项,则返回一个空数组),因此,在尝试访问 src 属性之前,您需要检查find返回的内容;

var ytThumb = $(this).find('img');
if (ytThumb.length > 0) {
    var ytLink = ytThumb[0].attr('src');
    // ... the rest of the code
}

编辑:在此期间得到了gabereal的回答。

相关文章: