大佬教程收集整理的这篇文章主要介绍了javascript – jQuery插件 – 如何添加/绑定事件,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我到目前为止
(function($) { $.tippedOff = function(SELEctor,setTings) { var config = { 'top':0,'left':0,'wait':3000 }; if(setTings){$.extend(config,setTings);} var $elem = $(SELEctor); if($elem.length > 0) { $elem.each(function() { $(this).css({"color":"#F00"}); }) } return this; }; })(jQuery);
这适用于更改提供的元素的文本颜色.然而.我想为插件生效的元素添加功能.例如悬停或点击事件.但是我现在无法理解这个想法,因为选择器可以是任何东西.所以它不像我可以通过普通的jQuery方法那样硬编码某些东西.
我已经为您提供了tippedOff插件的两个示例.这两个插件也是jsfiddle demo.
$.tippedOff = function(SELEctor,setTings);} var $elem = $(SELEctor); if($elem.length > 0) { $elem.each(function() { //bind mouseenter,mouSELEave,click event $(this).css({"color":"#F00"}) .mouseenter(function(){ $(this).css({"color":"green"}); }) .mouSELEave(function(){ $(this).css({"color":"#F00"}); }) .click(function(){ $(this).html('clicked'); }); }) } return this; };
但是,这个是基于您的原始代码.基本上,我已经使用these tips重建了你的原始代码.这就是我亲自去做的事情.我还向您提供了以下细分所做的更改. (重大变化):
$.fn.tippedOff = function(setTings) { var config = $.extend( { 'top':0,'wait':3000,'color': 'orange','hoverColor': 'blue' },setTings); return this.each(function() { $this = $(this); $this.css({ 'color': config.color}) .mouseenter(function(){ $this.css({ 'color': config.hoverColor }); }) .mouSELEave(function(){ $this.css({ 'color': config.color }); }) .click(function(){ $this.html('clicked'); }); }); }
—————————————-
分解:
原始代码:
$.tippedOff = function(SELEctor,setTings) {
更改:
$.fn.tippedOff = function( setTings ) {
@L_675_28@:
$.tippedOff和$.fn.tippedOff之间的差异很大!将插件添加到$.fn命名空间而不是$namespace将阻止您必须提供选择器并简化生活.
我个人喜欢this answer,其中@Chad声明:
原始代码:
if(setTings){$.extend(config,setTings);}
更改:
var config = $.extend( { 'top':0,'wait':3000 },setTings);
@L_675_28@:
拥有if语句是多余的. .extend()
为您完成所有工作.
原始代码:
var $elem = $(SELEctor); if($elem.length > 0) { $elem.each(function() { $(this).css({"color":"#F00"}); }) } return this;
更改:
return this.each(function() { $this = $(this); $this.css({ 'color': config.color}); });
@L_675_28@:
使用return this.each(function(){})是一种很好的做法并保持可链接性.不仅如此,您将不再需要担心选择器的长度.
*注意:如果要添加其他事件,请在插件中使用不同的方法:jQuery Doc Reference – Authoring Plugins.
我希望这有帮助,如果您有任何问题,请告诉我!
以上是大佬教程为你收集整理的javascript – jQuery插件 – 如何添加/绑定事件全部内容,希望文章能够帮你解决javascript – jQuery插件 – 如何添加/绑定事件所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。