javascript - 从 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.
}
});
解决方案
我不明白“返回事件”,但我猜你想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>
推荐阅读
- ansible - 如何将 aruba_command 与期望指令一起使用?
- c# - c#和进程控制
- elasticsearch - elasticsearch是否有文本到空间表的转换?
- mysql - 尝试在 MYSQL WORKBENCH 中创建视图但出现 1064 错误
- docker - VSCode devcontainer.json 挂载不起作用
- android - 我的视图模型数据未绑定到 edittext
- sql-server-data-tools - SSDT 单元测试配置覆盖是否适用于 VS 2015?
- c# - 如何生成带双引号的字符串并将其写入文本文件
- angular - 使用 FormBuilder 提交空对象
- r - 用 NA 替换 NULL 是列表