Passing variables in jquery

后端 未结 4 1960
小鲜肉
小鲜肉 2021-01-25 04:52

What is the best way to pass the var full to function b. I don\'t want to use global variables. Is return the only option.



        
相关标签:
4条回答
  • 2021-01-25 04:58

    argument? is there something im missing here?

    function b(x){ alert(x); }; 
    

    call with

    b(full);
    
    0 讨论(0)
  • 2021-01-25 05:07

    Unless you dont want function b to exist, or used outside outside of the click function, i would move it outside the anonymous function. And then just specify the arguments in the definition then just pass them like normal

    Example

    <script type="text/javascript">
        $("body").click(function(e){
            var name = $(e.target)[0].nodeName;
            var nameid = $(e.target)[0].id;
            var classname = $(name+"#"+nameid).attr('class');
            var full = name+"#"+nameid;
            console.log(nameid);
            b(full);
        });
        function b(full)
        {
            alert(full);
        };
    </script>
    
    0 讨论(0)
  • 2021-01-25 05:15

    You can pass a variable to a function by defining it as follows:

    function b(x) {
        alert(x);
    }
    

    and then calling it by stating its name and passing a variable as the argument:

    b(full);
    

    So in the context of your code:

    $("body").click(function(e){
        var name = $(e.target)[0].nodeName;
        var nameid = $(e.target)[0].id;
        var classname = $(name+"#"+nameid).attr('class');
        var full = name+"#"+nameid;
        console.log(nameid);
    
        function b(x){
            alert(x);
        };
    
        b(full);
    });
    
    0 讨论(0)
  • 2021-01-25 05:17
        // define b
        function b(full) {
            alert(full);
        }
    

    Actually, you aren't using global variables. You're defining them inside the JQuery anonymous function bound to the body element.

    0 讨论(0)
提交回复
热议问题