为什么jQuery on/off方法的行为与外部脚本不同 [英] Why does jQuery on/off method behave differently from external script
问题描述
在嵌入脚本时,单击标题可在问候/再见之间切换.为什么当代码在外部脚本中时,它只能连按两次才能工作?
Clicking the header toggles between hello/goodbye when the script is embedded. Why does it only work for two clicks when the code is in an external script?
嵌入式案例:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1 id="title" onclick="sayGoodbye();"> Hello </h1>
<script type="text/javascript">
function sayGoodbye() {
console.log("goodbye");
$("#title").html("Goodbye");
$("#title").click(function() {
$("#title").html("Hello");
$("#title").off("click");
});
};
</body>
</script>
外部情况:
<html>
<head>
<meta charset="UTF-8">
<title>Jquery click</title>
</head>
<body>
<h1 id="title"> Hello </h1>
<script src="jquery.js"></script>
<script src="click.js"></script>
</body>
</html>
这是click.js:
Here is click.js:
function sayGoodbye() {
console.log('goodbye');
$('#title').html('Goodbye');
$('#title').click(function () {
console.log('hello');
$('#title').html('Hello');
$('#title').off('click');
});
}
$(function(){$('#title').on('click', sayGoodbye);});
推荐答案
在第二个示例中,.off
将注销两个事件处理程序.来自文档:
In your second example, .off
is going to deregister both event handlers. From the docs:
如果提供了简单的事件名称(例如"click"),则会从jQuery集的元素中删除该类型的所有事件(直接事件和委托事件).
If a simple event name such as "click" is provided, all events of that type (both direct and delegated) are removed from the elements in the jQuery set.
在您的第一个示例中,这不是问题,因为您自己而不是通过jQuery的API来内联附加第一个处理程序.
In your first example this isn't an issue since you're attaching the first handler inline yourself, not through jQuery's API.
对此情况的更简洁的解决方案是简单地连接单个处理程序并维护/切换其状态:
A more concise solution to this case would be to simply hook up a single handler and maintain/toggle its state:
$(function () {
var isHere = true;
$('#title').click(function () {
$(this).html(isHere ? 'Goodbye' : 'Hello');
isHere = !isHere;
});
});
在事件中(不需要双关语),您只需要为一个调用连接一个事件处理程序,请不要忘记 one
也存在.
In the event (no pun intended) you ever do need to hook up an event handler for only one invocation, don't forget that one
also exists.
这篇关于为什么jQuery on/off方法的行为与外部脚本不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!