简体   繁体   English

如何根据当前元素的属性设置jQuery插件选项?

[英]How to set jQuery Plugin option based on attribute of current element?

I am setting up tooltips using qTip . 我正在使用qTip设置工具提示。 I am wondering how can I set an option based on a attribute of the current element? 我想知道如何根据当前元素的属性设置选项?

$('*[data-tip]').qtip({ // enable qTip on all elements that has the attribute 'data-tip'
    content: this.attr('data-tip'); // I can't get this to work, is it possible?
});

You need to use a .each() to have access to each element (as this ), like this: 您需要使用.each()来访问每个元素( this ),如下所示:

$('*[data-tip]').each(function() {
  $(this).qtip({
    content: $(this).attr('data-tip');
  });
});

However , *[data-tip] is a very expensive selector (and can just be [data-tip] ), if you can narrow it down so it's not checking for the attribute on every DOM element it would be much faster. 但是*[data-tip]是一个非常昂贵的选择器(可能只是[data-tip] ),如果你可以缩小它,所以它不会检查每个 DOM元素上的属性,它会更快。

Also, in jQuery 1.4.3+, you can replace $(this).attr('data-tip') with $(this).data('tip') , which looks at the data- attributes (if the key isn't present in the data object). 此外,在jQuery 1.4.3+中,您可以将$(this).attr('data-tip')替换$(this).data('tip') ,它会查看data-属性(如果键不是不存在于数据对象中。

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

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