1

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.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 

<style> 
    .aaa, .bbb, .ccc { width:100px; height:100px;background-color:#ccc;margin-bottom:5px;}
</style>
<body class="123">

    <p id="ptest"></p>
    <p class="aaa" id="aaaid"></p>
    <p class="bbb" id="bbbid"></p>
    <p class="ccc" id="cccid"></p>
    <div></div>
</body>
<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);

        function b(){
            alert(full);
        };
    });
</script>
1
  • You're not using b anywhere. Where is it called? Commented Jan 6, 2011 at 2:30

4 Answers 4

7

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);
});
Sign up to request clarification or add additional context in comments.

Comments

1

argument? is there something im missing here?

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

call with

b(full);

Comments

1
    // 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.

Comments

1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.