从Jquery方法中的函数中获取元素

时间:2013-01-23 17:05:58

标签: javascript jquery

我创建了一个jquery函数,需要运行一个用户函数onclick元素。问题是我需要访问我调用函数的元素。我将如何实现这一目标。该函数的一个例子是

                $("#domelement").yesNoDialog({
                 title:"Ineligible to Register",
                 message:"Stackoverflowtest",
                 yesFunction:function(){        
                     location.href = "www.stackoverflow.com"

                     //How do i grab an attribute from #domelement in here? ie $("domeElement").attr("stuff");

                 }
             });

Jquery方法的简化版本如下

(function($) {       
  $.fn.yesNoDialog = function(options) {     
    options = $.extend({}, $.fn.yesNoDialog.defaultOptions, options);      
    this.each(function() {
      $(this).click(function(){
          options.yesFunction();
       });
    });     
    return this;
  };
})(jQuery);

1 个答案:

答案 0 :(得分:3)

您可以将元素传入函数并以此方式使用

                $("#domelement").yesNoDialog({
                 title:"Ineligible to Register",
                 message:"Stackoverflowtest",
                 yesFunction:function(element){     
                     location.href = "www.stackoverflow.com"

                     //How do i grab an attribute from #domelement in here? ie $("domeElement").attr("stuff");

                 }
             });

将元素传递给函数

(function($) {       
  $.fn.yesNoDialog = function(options) {     
    options = $.extend({}, $.fn.yesNoDialog.defaultOptions, options);      
    this.each(function() {
      var that = this;
      $(this).click(function(){
          options.yesFunction(that); <--- Lets you use the element 
       });
    });     
    return this;
  };
})(jQuery);