javascript 在javascript中只调用一次js函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15584607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call js function only once in javascript
提问by Mahmood Rehman
I created js function and now i want that js function to call itself only once, My code is
我创建了 js 函数,现在我希望该 js 函数只调用一次,我的代码是
function view(str){
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/'+str+'/',
success: function(output_string){
//i want to call function from here only once like view(str);
}
});
}
. How can i do that ? Thanks in advance, Currently it is showing me infinte loop.
. 我怎样才能做到这一点 ?提前致谢,目前它向我展示了无限循环。
回答by Arun P Johny
Use a flag variable
使用标志变量
var myflag = false;
function view(str) {
$.ajax({
type : "POST",
url : '<?php echo base_url()?>index.php/main/' + str + '/',
success : function(output_string) {
if (!myflag) {
view(str);
}
myflag = true;
}
});
}
回答by Peter Rasmussen
You can pass a bool as a parameter on whether the function should call itself again:
您可以将 bool 作为参数传递给函数是否应该再次调用自身:
function view(str, shouldCallSelf){
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/'+str+'/',
success: function(output_string){
if (shouldCallSelf)
view(output_string, false)
}
});
}
You should call it with true the first time. It will then call itself with false the second time, will not execute again.
你应该第一次用 true 调用它。然后它会第二次用 false 调用自己,不会再次执行。
回答by Ray Cheng
you are looking for jquery one
.
http://api.jquery.com/one/
你正在寻找 jquery one
。
http://api.jquery.com/one/
fiddle http://jsfiddle.net/XKYeg/6/
小提琴http://jsfiddle.net/XKYeg/6/
<a href='#' id='lnk'>test</a>
$('#lnk').one('click', function view(str) {
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/' + str + '/',
success: function (output_string) {
i want to call
function from here only once like view(str);
}
});
});
回答by Aiias
Try adding a parameter to the function that keeps track of the count:
尝试向跟踪计数的函数添加一个参数:
function view(str, count) {
if (count > 0) {
return;
}
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/'+str+'/',
success: function(output_string) {
view(count + 1);
// i want to call function from here only once like view(str);
}
});
}
Then you would initially call view
like this:
然后你最初会这样调用view
:
view(str, 0);