[英]How make javascript function work only one time
How to make Javascript function work only one time ? 如何使Javascript函数只能运行一次?
if (window.location.hash) {
$(document).ready(function () {
var id = window.location.hash;
$(id).trigger('click');
});
$('li').click(function () {
$(this).prependTo($(this).parent());
});
}
I need auto-click on that li element which link user comes to website. 我需要自动单击链接用户进入网站的那个li元素。 web.com/#2 (list order - 2 1 3 4 5) , web.com/#4 (list order - 4 1 2 3).
web.com/#2(列表顺序-2 1 3 4 5),web.com /#4(列表顺序-4 1 2 3)。 but i want than user stay in website with hash url list elements stay in their places then user click for example on 3 list element he must stay and his place so list order (4 1 2 3).
但我想让用户停留在具有哈希URL列表元素的网站中,然后例如在用户必须单击的3列表元素上单击鼠标,然后单击其位置,以便列表顺序(4 1 2 3)。 I just need change list order by url hash on load page.
我只需要通过加载页面上的URL哈希更改列表顺序即可。
I solved it 我解决了
if (window.location.hash) {
$('li').one('click',function () {
if (!window.run){
$(this).prependTo($(this).parent());
window.run = true;
}
});
$(document).ready(function () {
var id = window.location.hash;
$(id).trigger('click');
});
}
In your particular case the simplest solution is to use .one()
, which unbinds the handler after running it the first time: 在您的特定情况下,最简单的解决方案是使用
.one()
,它在第一次运行处理程序后将其解除绑定:
$('li').one('click',function () { ... }
Another approach is to have the function redefine itself to a no-op after it runs. 另一种方法是让函数在运行后将其自身重新定义为无操作。 This can be useful in some cases when there isn't a convenient event handler to unbind:
在没有方便的事件处理程序解除绑定的某些情况下,这可能很有用:
var oneTimeFunction = function() {
console.log("This will only happen once.");
oneTimeFunction = function() {};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.