触发一个函数

jQuery - Trigger a function

本文关键字:一个 函数      更新时间:2023-09-26

我试图从位于js文件中的另一个函数的html文件触发一个函数。我试图使用trigger方法,但我不能使它工作。有什么建议吗?小提琴

<div id="result4" style="color:white; background:black">
  from function
</div>

<script>
  var TEST = new test({
    type: "image",
    file: "test.jpg",
    breakingPoint: 100
  });
  TEST.trigger('reset');
</script>

JS

function test(args) {
  $this.on('reset', function() {
    $("#result4").html("new text");
    console.log("OK");
  });
}

查看控制台日志,您的小提琴有一个错误:

$this.on('reset', function() {
  $("#result4").html("new text");
  console.log("OK");
});

$this未定义

和查看文档中的触发器:

http://api.jquery.com/trigger/

你调用它是错误的。您正在创建自己的对象,该对象没有trigger方法

你需要定义$this并返回它作为测试对象,因为触发器是一个jquery函数,而不是一个原生JavaScript对象函数。

    function test(args) {
       var $this = $(this); // declare $this
  var default_options = {
    breakingPoint: 2000
  };
  var options = $.extend({}, default_options, args);
  $("#result1").html(options.type);
  $("#result2").html(options.file);
  $("#result3").html(options.breakingPoint);
  $this.on('reset', function() {
    $("#result4").html("new text");
    console.log("OK");
  });
  return $this; 
}
var TEST = new test({
  type: "image",
  file: "test.jpg",
  breakingPoint: 100
});
TEST.trigger('reset');

将标记代码包装在jquery的ready事件中。这将在加载DOM时执行,而不是在解析DOM时执行。

也许这就是你要找的:

<script>
$(document).ready(function(){
    var TEST = test({
        type: "image",
        file: "test.jpg",
        breakingPoint: 100
    });
    TEST.reset();
});
</script>

In JS File

var test = function(options){
    var that = {};
    // you can use type, file & breaking point with option.type options.file etc..
    that.reset = function() {
        $("#result4").html("new text");
        console.log("OK");
    };
    return that;
};