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

Javascript 如何将方法附加/扩展到dom元素,javascript,jquery,Javascript,Jquery,拥有此html: <div id='hi1'> aaa </div> 我想得到一个提醒说“嗨” 有人知道这是怎么做到的吗?了解更多信息。jQuery方法啊,是的 jQuery.fn.sayHi = function() { // this is the jQuery object // so this[0] is a DOM element (or undefined) }; 阅读更多关于您实际上想要创建自己的名为:.sayHi的方法插件的信息 更多信息请点击

拥有此html:

<div id='hi1'> aaa </div>
我想得到一个提醒说“嗨”


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

了解更多信息。

jQuery方法啊,是的

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

阅读更多关于

您实际上想要创建自己的名为:.sayHi的方法插件的信息

更多信息请点击此处:

另一个例子:

$.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)                                
});

为什么不直接说美元?如果您不打算使用它,为什么要将它绑定到DOM元素@Jack我怀疑Chuck给出了一个过于简化的示例。你的HTML是错误的。你要关闭你的部门两次!这不是将方法附加到DOM,它的扩展jQuery。@Amberlamps,只有当它是xhtml时,在html5中才可以。
jQuery.fn.sayHi = function() {
  // this is the jQuery object
  // so this[0] is a DOM element (or undefined)
};
$.fn.sayHi = function() {
    alert($(this).text());
    return this;
};

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

$('#hi1').sayHi('hi');    // 'hi' will be passed to the jQuery method 'sayHy'
$.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)                                
});