简体   繁体   中英

how to access variable inside jquery from regular javascript function

I am a newbie to the jquery. I am trying to access a variable defined inside jquery block outside the jquery (from regular function) like this, but I can't access it. Could somebody tell me how?

<script language="javascript">
$(function()
{
    .......
    .......
    .......
    var api = pane.data('jsp');
    var current_location = api.getContentPositionX();
}

function change_title(t_index) {
    alert("print="+$.current_location);
    window.location.href="page.php?p="+$.current_location);
}

I want to get a value for $.current_location.

Thanks.

There is no such thing as a "jQuery variable", they are all regular Javascript varaibles.

The reason that you can't access the current_location variable from your function is that the variable is declared locally inside another function.

Just declare the variable outside the functions so that it's global, and you can access it from both functions:

var current_location;

$(function() {
    .......
    .......
    .......
    var api = pane.data('jsp');
    current_location = api.getContentPositionX();
}

function change_title(t_index) {
    alert("print=" + current_location);
    window.location.href = "page.php?p=" + current_location;
}

The jQuery object is global, as long as you have included jQuery on the page of course. So calling $.property or jQuery.property ($ is alias) should work as long as the property exists, is set and is public.

You might want to do in order to make the current_location var a member of the jQuery object:

$(function()
{
    .......
    .......
    .......
    var api = pane.data('jsp');
    this.current_location = api.getContentPositionX();
}

you need to store current_location on a globally accessible object. either window , or a custom object that you use as a namespaced object.

<script language="javascript">
var current_location = null;
var obj = {};
$(function() {
    .......
    .......
    .......
    var api = pane.data('jsp');
    current_location = api.getContentPositionX();
    obj.current_location = current_location;
})

function change_title(t_index) {
    obj.current_location;
    alert("print="+$.current_location);
    window.location.href="page.php?p="+current_location);
}

The variable is defined within the first function, so the scope of that variable is only within the first function and hence cannot be seen from outside that function.

Try defining the variable outside the function so it has a bigger scope.

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