开发者

Set VAR on click and alert the value

开发者 https://www.devze.com 2023-02-10 19:09 出处:网络
Why can\'t I get this to work?? I want to get the index() from the menu, and alert() the value when the hash changes, which it 开发者_如何学运维does.

Why can't I get this to work??

I want to get the index() from the menu, and alert() the value when the hash changes, which it 开发者_如何学运维does.

The alert doesn't appear.

    $('#menu li a').click(function() {
        var index = $(this).parent().index()+1;
    });



    $(window).bind('hashchange', function () { //detect hash change
        var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
        alert(index);
    });

Can you tell me what I'm doing wrong???


This is a scoping issue, the index variable is local to the function it's declared in, so you can't access it from the other function. Move the declaration to the outer scope and it will work:

var index;  // declare the variable
$('#menu li a').click(function() {
    // Assign the value, notice the `var` keyword isn't there anymore
    index = $(this).parent().index() + 1;
});

$(window).bind('hashchange', function() { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    // Get the value
    alert(index);
});

I suggest reading up on how scoping works in JavaScript - JS Garden has a decent overview.


The variable index is not in the same scope as the call to alert.

You may declare it as a global variable before both functions:

var index;

And then remove the var keyword in the first function:

$('#menu li a').click(function() {
    index = $(this).parent().index()+1;
});


    var index;
    $('#menu li a').click(function() {
        index = $(this).parent().index()+1;
    });



    $(window).bind('hashchange', function () { //detect hash change
        var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
        alert(index);
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号