简体   繁体   中英

jquery - using it on an input field - can't get variable out of function so I can use it

The first time I try to use my jQuery lessons on a real web page, I find that the variable guess (inside the scope of this inner function) disappears as soon as the function completes.

This is normal javascript behavior, I suppose, but how does one usually grab hold of the variable so one can use it in other functions? My lessons never covered that.

I assumed that once guess was routed into the innerHTML of #display , it would stick. But it's even disappearing from there.

?

<!DOCTYPE html>
<html>
    <HEAD>
        <title>Game of the Century</title>
        <meta charset="UTF-8">
        <LINK href="reset.css" rel="stylesheet" type="text/css">
        <LINK href="main.css" rel="stylesheet" type="text/css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="application.js"></script>
    </HEAD>

    <body>
        <form>
            <input type='text' name = "input" id = "input"><br>
            <input type='submit' id="submit">
        </form>
        <p id = "display"></p>   
        <div>
            <img src="http://img707.imageshack.us/img707/2403/rj1a.jpg" alt = "ad">
        </div>
    </body>
</html>

...

$(document).ready(function () {

        $('#submit').click( function() { 
              var guess = $('#input').val();
              $("#display").html(guess);
         });   

});

This is absolutely normal and it is not related to jQuery. Your guess variable is defined in a closure, anonymous function. So, it lives there and it is not accessible outside of that scope. If you want to use guess outside the click handler, just define it outside. For example:

$(document).ready(function () {
    var guess;
    $('#submit').click( function() { 
        guess = $('#input').val();
        $("#display").html(guess);
    });   
    var anotherMethod = function() {
        alert(guess); // <--- it works
    }
});

Also, you don't need to use document.getElementById if you already include jQuery.

Edit: I just saw the html. There is another side effect of the code. Your form is actually submitting when you click the button. Try changing the type="submit" to "type="button" or some other way to prevent the form submitting.

Just here my solution with perhaps a better split of read/write tasks

    $(document).ready(function () {

        getMyHtml = function() {
            return $('#input').val();
        }

        setMyHtml = function () {
            var s = getMyHtml();
            $("#display").html(s);
        }

        $('#submit').click(setMyHtml);
    });   

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