使用 $(this) 的属性

Using attributes of $(this)

本文关键字:属性 this 使用      更新时间:2023-09-26

老实说,我不知道我的问题是否与我正在使用的插件相关的jQuery有关。

我使用插件 RateYo (http://prrashi.github.io/rateYo/) 在我们的网站上显示星星。需要显示的星星数在div 的属性中给出:

<div id="rating-avg" class="rateyo" rating="<?php echo $avg_rating; ?>" preset="true"></div>

然后,我通过调用 home.js 来调用插件 RateYo,其中包含:

jQuery.noConflict()(function($){
$(document).ready(function() {
    $(".rateYo").rateYo({
        rating: $(this).attr('rating'),
        readOnly: $(this).attr('preset')
    });
});

});

不幸的是,这不起作用。该插件确实启动并创建了星星,但没有使用变量 $(this).attr('rating') 和 $(this).attr('preset')。不显示评级,而是显示空星。

当我使用以下代码时,评级完美显示:

    $("#rating-avg").rateYo({
        rating: $("#rating-avg").attr("rating"),
        readOnly: $("#rating-avg").attr("preset")
    });

不幸的是,我需要插件按类而不是 id 启动。我们在网站上有可变数量的评级,因此无法按 ID 选择它们。

有人看到我做错了什么吗?

您的this值将不正确,并且您的类名使用了错误的大写字母。 您可能可以使其像这样工作:

$(".rateyo").each(function() {
     var item = $(this);
     item.rateYo({
         rating: item.attr('rating'),
         readOnly: item.attr('preset')
     });
});

请注意,您可能应该使用 HTML5 数据属性,而不是您自己的自定义属性:

<div id="rating-avg" class="rateyo" data-rating="<?php echo $avg_rating; ?>" data-preset="true"></div>
$(".rateyo").each(function() {
     var item = $(this);
     item.rateYo({
         rating: item.data('rating'),
         readOnly: item.data('preset')
     });
});
你在

jQuery代码中引用rateYo,而class属性包含没有大写字母"Y"的rateyo