简体   繁体   中英

How to get variables in an anonymous function in jQuery?

How to pass variables to an anonymous function. I want to pass few variables to an anonymous function, based on the function, it will create a new string. In this code, i want to pass url, timestamp, id and plan.

  <script>
        jQuery(document).ready(function() {
            console.log("check")
            var newUrl=url+'?id='+id+'&timestamp='+timestamp+'&plan='+plan;
            console.log(newUrl);
            createStoryJS({
                type:       'timeline',
                width:      '1250',
                height:     '240',
                source:     newUrl,
                embed_id:   'my-timeline'
            });
        });
    </script>

You can declare a variable with global scope and use it inside the function call as below

var globalVar = 1;
jQuery(document).ready(function() {
    console.log(globalVar);
});

The argument to the ready handler is passed by jQuery and is set to the jQuery object (see https://api.jquery.com/ready/ > Aliasing the jQuery Namespace). So you can't pass it into the function declaration in your above code.

You could set it to a global object or set a form field and then read it from inside your function. Fiddle for the latter - http://jsfiddle.net/eqz7410c/

HTML

<form>
    <input id="b" type="hidden" value="123" />
</form>

JS

$(document).ready(function() {
    alert($("#b").val())
});

First of, jQuery(document).ready(function() {}); would be the entry point of document when it is ready to be accessed. There are several approaches to this.

The idea is you do not need to pass anything but use your resources you created in this anonymous function.

I want to pass few variables to an anonymous function, based on the function , it will create a new string.

I would not recommend you to use global variables. That function from which you probably get those values for id , timestamp and plan should return you that sting itself which you can assign to newUrl inside document ready function. You can use a closure also.

function returnUrl(){
  // code to calculate id, timestamp and path..
  // ....
  // ....
  return url+'?id='+id+'&timestamp='+timestamp+'&plan='+plan;
}

jQuery(document).ready(function() {
// DOM ready to access..
    console.log("check")
    var newUrl = returnUrl();
    console.log(newUrl);
    createStoryJS({
        type:       'timeline',
        width:      '1250',
        height:     '240',
        source:     newUrl,
        embed_id:   'my-timeline'
    });
});

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