javascript - (this) 在 jQuery 中的用法

标签 javascript jquery this

我有下面这样的 HTML 元素

<div class="myclassname" data-barcolor="#000000"></div>

我正在尝试使用 (this) 获取这些“data-barcolor”属性。关键字,而不是使用类名..如下所示

$('.myclassname').easyPieChart({
    barColor : $(this).attr('data-barcolor'),
});

它不能正常工作。 但是

$('.myclassname').easyPieChart({
    barColor : $('.myclassname.').attr('data-barcolor'),
});

完美运行。

通过使用类名,我无法动态获取值。我有多个具有不同值的同名类(class)。那么如何在 jquery 中获取值呢!

最佳答案

您可以为此使用each 循环:

$('.myclassname').each(function() {
    $(this).easyPieChart({
        barColor : $(this).data('barcolor'),
    });
});

文档还指出 barColor 可以是一个函数,但是不幸的是,这个函数是在错误的上下文中调用的(正如我从阅读 sources 可以假设的那样)所以你不能使用自然的 barColor: function() { return $(this).attr(...); 方式。

关于javascript - (this) 在 jQuery 中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561751/

相关文章:

javascript - 如何切换选中所有复选框

javascript - 多类别复选框

javascript - JQuery ajax 使用复选框对象回发 id

javascript - 为什么 JSLint 禁止 "this"关键字?

javascript - 正则表达式如何用一个空格替换多个空格

javascript - 使链接在点击时动态激活

javascript - Jquery 在 DropDownList/SELECT 项目上激活已更改

javascript - 我怎样才能得到每个 "a"标签,其中 "href"属性包含单词 "youtube"?

javascript - 在函数 javascript dojo 工具包中使用 this 关键字

c++ - 为什么没有 'this_class' - 'this' 的静态等价物?