下面是一个编辑,用于将事件从文档加载移动到正在单击的按钮。
<!DOCTYPE HTML>
<html>
<head>
<title>Long task</title>
<script src="https://code.jquery.com/jquery-3.6.3.js"></script>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).on('click', '.widget input', function (event) {
namespace = '/test';
var socket = io(namespace);
socket.on('connect', function() {
$('#messages').append('<br/>' + $('<div/>').text('Requesting task to run').html());
socket.emit('do_task', {duration: '60'});
});
socket.on('task_done', function(msg, cb) {
$('#messages').append('<br/>' + $('<div/>').text(msg.data).html());
if (cb)
cb();
});
event.preventDefault();
});
</script>
</head>
<body>
<div class="widget">
<input type="submit" value="Click me" />
</div>
<h3>Messages</h3>
<div id="messages" ></div>
</body>
</html>