I have a function that I want to call again inside, after the last line finishes.
我有一个函数,我想在最后一行结束后再次调用。
Maybe it will be more understandable if I show code.
如果我展示代码,也许会更容易理解。
function updateQuantity(){
// further code where I change same data
// and now I want to start function again but with remembering the input element that called it previously
updateQuantity(this); // I tried it this way but it doesn't work
}
Any idea?
3 个解决方案
#1
3
From the comments to your question, it seems like you want to pass a value to your recursive method call.
从评论到您的问题,您似乎想要将值传递给递归方法调用。
function updateQuantity(val){
// Do something with `val`
val = val + 1;
console.log(val);
// And call it again with the value
if(val < 5){
updateQuantity(val);
}
}
updateQuantity(1); // 2, 3, 4, 5
#2
3
The answer is simple, it is enough to use updateQuantity.call(this)
inside the updateQuantity
function - when we use call
and add this
, the function will start again and remember the input element that previously called updateQuantity
.
答案很简单,在updateQuantity函数中使用updateQuantity.call(this)就足够了 - 当我们使用call并添加它时,该函数将重新启动并记住之前调用updateQuantity的输入元素。
#3
0
it looks like you are trying to get that DOM element in the function body.
看起来你正试图在函数体中获取DOM元素。
this is a simple example.
这是一个简单的例子。
link to Fiddle https://jsfiddle.net/c3kbu0j7/10/
链接到Fiddle https://jsfiddle.net/c3kbu0j7/10/
html
<a href="#">element you want.</a>
javasript
$('a').on('click',function(){
a(this);
});
var i=0;
function a(tar){
console.log(tar);
if(i<4){
i++;
a(tar);
}
i=0;
}
#1
3
From the comments to your question, it seems like you want to pass a value to your recursive method call.
从评论到您的问题,您似乎想要将值传递给递归方法调用。
function updateQuantity(val){
// Do something with `val`
val = val + 1;
console.log(val);
// And call it again with the value
if(val < 5){
updateQuantity(val);
}
}
updateQuantity(1); // 2, 3, 4, 5
#2
3
The answer is simple, it is enough to use updateQuantity.call(this)
inside the updateQuantity
function - when we use call
and add this
, the function will start again and remember the input element that previously called updateQuantity
.
答案很简单,在updateQuantity函数中使用updateQuantity.call(this)就足够了 - 当我们使用call并添加它时,该函数将重新启动并记住之前调用updateQuantity的输入元素。
#3
0
it looks like you are trying to get that DOM element in the function body.
看起来你正试图在函数体中获取DOM元素。
this is a simple example.
这是一个简单的例子。
link to Fiddle https://jsfiddle.net/c3kbu0j7/10/
链接到Fiddle https://jsfiddle.net/c3kbu0j7/10/
html
<a href="#">element you want.</a>
javasript
$('a').on('click',function(){
a(this);
});
var i=0;
function a(tar){
console.log(tar);
if(i<4){
i++;
a(tar);
}
i=0;
}