首页 > 解决方案 > 从 jQuery 函数返回事件

问题描述

函数完成运行后,如何将事件返回给调用函数以执行某些操作。

jQuery 函数

$.fn.myFunction(){
    this.each(function(){
        var it = $(this)
        setTimeout(function(){
            /* Return an event */
        }, 3000);
    }
}

调用 jQuery 函数

$('div.specific').myFunction({
    'finish': function(element){
        /* Do something with element.
    }
});

标签: javascriptjquery

解决方案


我不明白“返回事件”,但我猜你想finish在事情完成时调用函数。

我不确定这是最好的方法,但你可以从它开始。

$.fn.myFunction = function (object) {

	const _self = $(this);
	const init = () => {    
    if (object.hasOwnProperty('myCallback') && typeof object.myCallback === 'function') {
    	_self.on('myEvent', object.myCallback)
    }
    
    _self.on('click', triggerCustomEvent)
  };
  
  const triggerCustomEvent = () => _self.trigger('myEvent')
  
  init();
}


$('#c').myFunction({
	myCallback: () => alert(123),
})
$('#d').myFunction({
	myCallback: () => alert(1234),
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="banner-message">
  <button id="c">Color</button>
  <button id="d">Dollar</button>
</div>


推荐阅读