从外部触发jQuery插件中的事件

时间:2019-11-27 12:22:51

标签: javascript jquery easyautocomplete

我使用简单的autocomplete jQuery插件,该插件具有内部事件“ onSelectItemEvent”。

现在我想从外部调用此事件(因为它已经绑定到我已经编写的扩展功能)。

我准备了一个小提琴,但是以此触发插件事件不起作用:)

$("#example-ac").easyAutocomplete(this.list.onSelectItemEvent());
$(document).ready(function() {
  var options_ac = {
    url: "https://fcgi.msk.link/model-json.pl?site=test",
    getValue: function(element) {
      //console.log(element);
      return element;
    },
    list: {
      match: {
        enabled: true
      },
      sort: {
        enabled: true
      },
      maxNumberOfElements: 8,
      onSelectItemEvent: function() {
        $("output").html($("#example-ac").val())
      }
    },
    theme: "square"
  };
  $("#example-ac").easyAutocomplete(options_ac);

  $("#trigga").click(function() {
    $("#example-ac").easyAutocomplete(this.list.onSelectItemEvent());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.themes.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/jquery.easy-autocomplete.min.js"></script>

<input id="example-ac" />
<br>
<input id="example-ac" /><br/>
<output></output>
<button id="trigga">
trigger
</button>

http://jsfiddle.net/Lgetus29/

如果此方法可行,或者必须以其他方式解决问题,则表示感谢。 codepen的例子只是很小的代码,而对于这个内部函数的实际编码却很庞大,所以我想重用。也许我最好在插件之外创建一个函数,然后在“ onSelectItemEvent()”中重用此函数,甚至可能吗?

谢谢!!

1 个答案:

答案 0 :(得分:1)

为什么不像

那样使用它
$("#trigga").click(function() {
    options_ac.list.onSelectItemEvent()
});

因此您的最终代码将如下所示

$(document).ready(function() {
    var options_ac = {
        url: "https://fcgi.msk.link/model-json.pl?site=test",
        getValue: function(element) {
        //console.log(element);
            return element;
        },
        list: {
            match: {
                enabled: true
            },
            sort: {
                enabled: true
            },
            maxNumberOfElements: 8,
            onSelectItemEvent: function() {
                $("output").html($("#example-ac").val())
            }
        },
        theme: "square"
    };
    $("#example-ac").easyAutocomplete(options_ac);

    $("#trigga").click(function() {
        options_ac.list.onSelectItemEvent();
    });
});