0

I'm trying to make a variable in a function, that I can then redefine using it again in a different function, and I was wanting to use jquery .data to do it but am unsure how.

I have this

$(".photo").click(function() {
  var id = $(this).attr('id');
});

in the next function I'd like to redefine the id variable...using the previous id variable value, any ideas on how to do this?

$("#next").click(function() {  
  var id = $(id).next().attr('id');
});

3 Answers 3

0

the answer is global variables, so it ended up being like this:

$(".photo").click(function() {
    id = $(this).attr('id');
});

$("#next").click(function() {  
      var id_a = $('#' + id).next().attr('id');
      id = id_a;
});

$("#prev").click(function() {  
      var id_b = $('#' + id).prev().attr('id');
      id = id_b;
});
0

You need to define that variable globally so other function can use it.

Sample Tested Code

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

    $(function()
    {
        var GlobalScope;

        $('#boxes').click(function()
        {
            GlobalScope = $.trim($(this).html());
        });

        $('#boxes_').click(function()
        {
            console.log(GlobalScope);
        });
    });

</script>

<div id="boxes">
    One
</div>

<div id="boxes_">
    Two
</div>

When you click on boxes it will set GlobalScope variable value as One now after click boxes when you click on boxes_ GlobalScope value will be One in Console.log.

0

You need to define new common variable for both functions as @loriensleafs's answer.

Additionally, i recommend using Closure for prevent scope issue.

(function() {
    var id;    // common value but canb be accessed only in this function.

    $(".button").click(function() {
        id = $(this).attr('id');
    });

    $("#output").click(function() {  
        $("p").css( "background", "none" );
        $("div").find('#' + id).css( "background", "red" );
    });
})();

check http://jsfiddle.net/cwdoh/G2RjH/2/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.