简体   繁体   中英

How to call function inside itself

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?

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

答案很简单,在updateQuantity函数中使用updateQuantity.call(this)就足够了 - 当我们使用call并添加this ,该函数将再次启动并记住之前调用updateQuantity的输入元素。

It looks like you are trying to get that DOM element in the function body.

This is a simple example: https://jsfiddle.net/c3kbu0j7/10/

HTML

<a href="#">element you want.</a>

JavaScript

$('a').on('click',function(){
    a(this);
});
var i=0;
function a(tar){
  console.log(tar);
  if(i<4){
    i++;
    a(tar);
  }
  i=0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM