0

有这个html:

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

做的时候:

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

我想收到一个说“嗨”的警报

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

4

5 回答 5

4

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

于 2012-06-01T10:07:53.270 回答
3
$.fn.sayHi = function() {
    alert($(this).text());
    return this;
};

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

演示

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

于 2012-06-01T10:09:33.727 回答
2

jQuery 方法啊啊啊啊!

jQuery.fn.sayHi = function() {
  // this is the jQuery object
  // so this[0] is a DOM element (or undefined)
};
于 2012-06-01T10:08:07.287 回答
2
$.fn.extend({ sayHi:function(){ alert('hi'); }); 
于 2012-06-01T10:08:00.777 回答
1

您实际上想创建自己的方法(插件),称为:.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

于 2012-06-01T10:11:58.547 回答