【问题标题】:jQuery call a function from outside a custom functionjQuery 从自定义函数外部调用函数
【发布时间】:2021-10-15 16:15:30
【问题描述】:

也许我没有正确用词。但我有一个我创建的自定义 jQuery 函数。现在在函数之外,我希望能够调用其内部函数之一。

示例:https://jsfiddle.net/dmcqe1fj/

在 jsFiddle 示例中,我有两个简单的文本框。自定义函数将确认它们的文本是否匹配。我想访问该函数中的一个函数。

注意:我知道我可以通过简单地在函数外部测试等效性来获得相同的结果,但我特别想看看你如何从自定义函数外部调用内部函数(如果可能的话)


$(function() {
  
  $.fn.Test = function() {
    const $master = this;
    
    const $t1 = $master.find(".txt1"),
          $t2 = $master.find(".txt2"),
          $notice = $master.find(".notice");
    
    function Check() {
      $notice.removeClass("error success").hide();
      if ($t1.val().length === 0 && $t2.val().length === 0) {
        return;
      }
      if ($t1.val() == $t2.val()) {
        $notice.addClass("success").text("Text Matches!").show();
      }
      else{
        $notice.addClass("error").text("Text Does Not Match").show();
      }
    }
    
    $t1.on("keyup", Check);
    $t2.on("keyup", Check);
    
    /****** THIS IS THE FUNCTION I WANT TO ACCESS ********/
    function GetResult() {
      return $t1.val() == $t2.val();
    }
    
  };
  
  let $test = $("#container").Test();
  
  $("#btn").on("click", function() {
    console.log($test.GetResult());  // This is not valid
    
    /*
      I know the same result can be achieved:
          console.log($(".txt1").val() == $(".txt2").val());
       
      BUT I AM SPECIFICALLY LOOKING TO SEE HOW 
      TO CALL A FUNCTION WITHIN A CUSTOM FUNCTION
    */
  });
  
  
});

【问题讨论】:

    标签: jquery custom-function


    【解决方案1】:

    您可以尝试为您的函数创建更“面向对象”的方法:

    function parentFunction()
    {
        this.childFunction = function(){
            return 'hello world';
        };
    }
    
    var $test = new parentFunction();
    
    console.log( $test.childFunction() );
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 2014-01-31
      相关资源
      最近更新 更多