繁体   English   中英

如何将方法附加/扩展到dom元素

[英]how to attach/extend methods to dom element

有这个HTML:

<div id='hi1'> aaa </div>

进行时:

$('#hi1').sayHi();

我想收到警告说“嗨”

有人知道这是怎么做的吗?

阅读有关jQuery插件创作的更多信息。

$.fn.sayHi = function() {
    alert($(this).text());
    return this;
};

$('#hi1').sayHi();

演示

阅读有关jQuery插件的更多信息

$.fn.extend({ sayHi:function(){ alert('hi'); }); 

jQuery方法aaaaw是的!

jQuery.fn.sayHi = function() {
  // this is the jQuery object
  // so this[0] is a DOM element (or undefined)
};

您实际上想创建自己的方法(插件) .sayHi()

演示jsFiddle

$.fn.sayHi = function(something){   
    alert(something);       
};

$('#hi1').sayHi('hi');    // 'hi' will be passed to the jQuery method 'sayHy'

此处提供更多信息: http : //docs.jquery.com/Plugins/Authoring

另一个例子:

$.fn.sayHi = function(txt, clr){   
     this.css({color: clr}).text(txt); // 'this' is your element delegated to your plugin
};

$('#hi1').click(function(){   
    $(this).sayHi('Heading is clicked!', 'red');  // (txt, crl)                                
});

演示2

暂无
暂无

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

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