<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<title>test</title>
<style type="text/css">
.button_test{
border-radius: 4px;
padding: 4px;
cursor: pointer;
background-color:#999;
}
</style>
</head>
<body>
<span class="button_test">debug</span>
<script type="text/javascript">
var testFunction = function(_callback){
$(".button_test").click(function(){
if ("function"==typeof(_callback)) {
_callback();
};
})
}
testFunction(function(){
console.log(111);
});
</script>
</body>
</html>
函数testFunction只使用过一次,所以我想当我第一次clcik $(".button_test")
时,控制台会输出111。然后无论我使用多少次点击 $(".button_test")
,控制台不会输出任何内容。
然而,事实上,每次点击 $(".button_test")
时,控制台都会输出 111。
最佳答案
Click 不会运行一次事件,而是在每次事件发生时运行。阻止它的唯一方法是取消绑定(bind)事件或在内部添加一个标志以表示不运行。但是有一个更好的方法,因为 jQuery 有一个方法可以运行一次事件,那就是 one()
one()
.one( events [, data ], handler(eventObject) )
Returns:jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
你的代码可以像这样使用它
var testFunction = function(_callback){
$(".button_test").one("click", function(){
if ("function"==typeof(_callback)) {
_callback();
};
})
}
testFunction(function(){
console.log(111);
});
关于javascript - 这个函数(testFunction)有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21728858/