1

我制作了一个 jquery 函数,该函数需要在元素的单击上运行用户函数。问题是我需要访问我正在调用该函数的元素。我将如何实现这一目标。该函数的一个示例是

                $("#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 Method的简化版如下

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

1 回答 1

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);
于 2013-01-23T19:19:52.870 回答