简体   繁体   中英

Global variable in javascript result is always undefine

I had trouble with my global variable hope you can help me.

<li>
 <a href="<?php echo site_url("adminController/questionAdd/".$row->subjectid); ?>" id="<?php echo $row->subjectid; ?>" class="subject">Add Question</a>
</li>

Now from that line I passed my id in this line by click() in javascript

$(document).ready(function () {
        var correctAnswer;
        var subId;

        $( ".subject" ).click(function() {
            subId = ($(this).attr('id')); //passed the id variable into the global variable
            alert(subId) // when I alert this it returns the value
        });

now I used the global variable in this line the same $(document).ready(function ()

$('#form-user').submit(function(e){
                e.preventDefault();

                var me = $(this);
                var correct = correctAnswer;
                var passedSubId = subId; // passed the global variable to this local variable 
                console.log(correct); // this is okey
                console.log(subId); // this is undefined
});

result

i
undefined

You can use window to declare a global variable though it is h ighly recommended not to use.

You can declare a global variable like this:

window.yourVariable = "something";

Your code will never work as you think it will.

What you are doing there I think is you click on your link, which then moves you from page A to page B, and you want to use that variable that you set on page A on page B, sorry but this will never work, when you refresh your page your entire script is run again and it does not know what have you done on the previous page. You would have to either take that id from the url ( its there ) or store it for example in local storage , try this:

$(document).ready(function () {
    var correctAnswer;
    var subId;

    $( ".subject" ).click(function() {
        subId = ($(this).attr('id')); //passed the id variable into the global variable
        alert(subId) // when I alert this it returns the value
        localStorage.setItem('subId', subId);
        console.log('id stored');
    });

    $('#form-user').submit(function(e){
            e.preventDefault();

            var me = $(this);
            var correct = correctAnswer;
            var passedSubId = subId; // passed the global variable to this local variable 
            console.log(correct); // this is okey
            console.log(subId); // this is undefined

            storedSubId = localStorage.getItem('subId');
            alert(storedSubId); 
            console.log('stored id');
    });
});

Anyway getting it from url is definitely the way you want to go

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