Pass a value from function to other functions in Javascript

前端 未结 3 711
独厮守ぢ
独厮守ぢ 2020-12-22 12:52

I need to get a value from an HTML input in a javascript function. I can successfully get the value form the HTML but I couldn\'t pass that from 1 function to other. And I n

相关标签:
3条回答
  • 2020-12-22 13:03

    PageKey() is just getting the value, but it does not return it. So, you need to add return val; to PageKey(). Then, in fun3, you can set a variable to what's returned from PageKey(). So, you would end up with this:

    var PageKey = function(){
     var val = document.getElementById('demo').value;
     return val;
    }
    
     var fun1 = function(data){
    
     }
    
     var fun2 = function(data){
    
     }
    
     var fun3 = function(data){
       var val = PageKey();
       console.log(val);
       // prints out what PageKey got
       fun1(val);
       fun2(val);
     }
    
    0 讨论(0)
  • 2020-12-22 13:18

    If you want to pass the value that you get in PageKey to some other function, you need to add a return statement to PageKey.

    var PageKey = function(){
     return document.getElementById('demo').value;
    }
    

    Now you'd be able to do this:

     var fun3 = function(data){
       var demoValue = PageKey();
      // and then do whatever with demoValue
     }
    
    0 讨论(0)
  • 2020-12-22 13:26

    You have to return the value

    var PageKey = function(){
        var val = document.getElementById('demo').value
        return val;
    }
    

    And then

    var fun3 = function(){
        return PageKey();
    }
    
    0 讨论(0)
提交回复
热议问题