【问题标题】:jQuery - .attr is not a functionjQuery - .attr 不是函数
【发布时间】:2016-12-16 07:56:20
【问题描述】:

构建了一个 WordPress 插件,该插件基于包含 You Tube 视频 ID 的短代码创建自定义样式的视频播放器,并且效果很好。但现在我必须将其转换为允许同一页面上的多个视频。所以我通过类名获取所有玩家元素,然后获取他们的 ID。 YouTube 视频 ID 附加到每个播放器的 data-id 属性。在插件的单视频版本中,我可以使用$(#playerid).att('data-id')来抓取属性。在 v2.0 中发生了两件奇怪的事情……首先是我不能再使用$ 来指定 jQuery 对象,因为 WordPress 使用了兼容模式(也许我应该想知道为什么我在以前的版本中可以使用 $。 ..),但这很容易解决。第二个问题是我无法使用attr。它说

attr 不是函数。

我尝试了 .attr('data-id')、.data('id') 并转换为 vanilla .getAttribute,但没有任何效果。我检查了变量是否指向到正确的对象,但我无法获得它的属性...有什么帮助吗?

我将只发布第一行,直到您到达attr...

var playerids = [];
var players = document.getElementsByClassName("video-player");

for (x = 0; x < players.length; x++) {
    playerids[x] = players[x].id;
}

//for each vidid, create a player
for (i = 0; i < players.length; i++) {

    var video_id = jQuery(playerids[i]).attr('data-id');
}

新信息: 将全局变量从 Vanilla 更改为 jQuery,现在我可以在全局变量上使用 .attr 或 .data。这是我的新的工作代码...为什么它可以工作,而本地变量却没有?

//find all player divs
var players = jQuery(".video-player");

//get the player div ids
var playerids = [];
for (x = 0; x < players.length; x++) {
    playerids[x] = players[x].id;
}

//for each player div, get vidid and create player
for (i = 0; i < players.length; i++) {

    var this_video = jQuery(players[i]).data('id');

【问题讨论】:

  • 你是否包含了 jquery 库?

标签: javascript jquery wordpress youtube attributes


【解决方案1】:

你可以试试这个代码吗:

var video_id = jQuery('#' + playerids[i]).attr('data-id');

因为 playerids[i] 只有像“playerid”这样的播放 id

【讨论】:

    【解决方案2】:

    您的代码中明显有问题的是在 jQuery(playerids[i]).attr('data-id'); 处分配一个没有 # 符号的 id 选择器

    正确的语法应该是: jQuery('#' + playerids[i]).attr('data-id');

    如果使用id 选择器不是隐式的,试试这个:

    jQuery( ".video-player" ).each(function( index ) {
      console.log( index + ": " + jQuery(this).attr('data-id') );
    });
    

    【讨论】:

    • 哎呀 - 回想起来,不附加“#”是非常明显的......但即使添加了它,它仍然告诉我 .attr(或 .data)不是一个函数。跨度>
    • 使用 console.log 我可以看到控制台中回显了正确的值,但我不熟悉该方法——如何在我的函数中检索这些值? (这种方法是好的做法吗?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2020-10-11
    • 2010-11-14
    相关资源
    最近更新 更多