gpt4 book ai didi

javascript - 在新插件中使用 attr() 函数?

转载 作者:太空狗 更新时间:2023-10-29 15:55:37 24 4
gpt4 key购买 nike

我想知道是否可以在新插件中使用 attr() 函数:

(function ($) {
$.fn.resetColor = function() {
var oldColor=this.attr("memColor");
this.css('background-color',oldColor);
};
})(jQuery);

我试过上面的代码,但它不起作用。我确定 memColor 属性存在,因为我已经在 $(document).ready block 中使用警报对其进行了测试。

最佳答案

jQuery插件authoring guidelines推荐这个方法:

(function ($) {
$.fn.resetColor = function() {
return this.each(function() {
var elem = $( this );

var oldColor = elem.attr("memColor");
elem.css('background-color',oldColor);
};
});
}(jQuery));
  1. 假设插件在一组元素上被调用。
  2. 获取要使用的 jQuery 包装元素。

另请注意,properties ( prop() ) 和 attributes ( attr() ) 之间存在差异,前者指的是 JavaScript DOM HTMLElements 上的属性,而后者指的是标记中指定的 HTML 属性。从 1.6 版开始,jQuery 也做出了这种区分:

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.


演示:

    (function ($) {
$.fn.resetColor = function() {
return this.each(function() {
var elem = $( this );

var oldColor = elem.attr("memColor");
elem.css('background-color',oldColor);
});
};
$('.me').resetColor();
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="me" memColor="Red">Lorem ipsum.</div>
<div class="me" memColor="Blue">Lorem ipsum.</div>

关于javascript - 在新插件中使用 attr() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27475893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com