[removed] get a function's variable's value within another function

前端 未结 5 1465
故里飘歌
故里飘歌 2020-12-08 21:20

okay so I have this code in body:


And this code in script

<         


        
相关标签:
5条回答
  • 2020-12-08 22:05

    the OOP way to do this in ES5 is to make that variable into a property using the this keyword.

    function first(){
        this.nameContent=document.getElementById('full_name').value;
    }
    
    function second() {
        y=new first();
        alert(y.nameContent);
    }
    
    0 讨论(0)
  • 2020-12-08 22:06

    nameContent only exists within the first() function, as you defined it within the first() function.

    To make its scope broader, define it outside of the functions:

    var nameContent;
    
    function first(){
        nameContent=document.getElementById('full_name').value;
    }
    
    function second() {
        first();
        y=nameContent; alert(y);
    }
    second();
    

    A slightly better approach would be to return the value, as global variables get messy very quickly:

    function getFullName() {
      return document.getElementById('full_name').value;
    }
    
    function doStuff() {
      var name = getFullName();
    
      alert(name);
    }
    
    doStuff();
    
    0 讨论(0)
  • 2020-12-08 22:07

    you need a return statement in your first function.

    function first(){
        var nameContent = document.getElementById('full_name').value;
        return nameContent;
    }
    

    and then in your second function can be:

    function second(){
        alert(first());
    }
    
    0 讨论(0)
  • 2020-12-08 22:09

    Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

    <script language="javascript" type="text/javascript">
        var nameContent; // In the global scope
        function first(){
            nameContent=document.getElementById('full_name').value;
        }
    
        function second() {
            first();
            y=nameContent; 
            alert(y);
        }
        second();
    </script>
    
    0 讨论(0)
  • 2020-12-08 22:17

    Your nameContent scope is only inside first function. You'll never get it's value that way.

    var nameContent; // now it's global!
    function first(){
        nameContent = document.getElementById('full_name').value;
    }
    
    function second() {
        first(); 
        y=nameContent; 
        alert(y);
    }
    second();
    
    0 讨论(0)
提交回复
热议问题