简体   繁体   中英

Why does it work in jsfidde but not on my browser?

Please check out this jsfiddle:

http://jsfiddle.net/xNEZH/2/

It works fine in my jsfiddle

[BOX APPEARS WHEN TEXT IS INPUTTED IN INPUT]

but doesn't work on my browsers BUT I am using the latest versions of safari, firefox and chrome.

What is the matter?

HTML / JAVASCRIPT CODE:

<html>
<head>

<script type="text/javascript" src="jquery-1.7.js"></script>
<script>
$(document).ready(function () {
(function watchInputForChanges(){
    var hasInput = $('.input1').val() != "";
    $('.box')[hasInput ? 'show' : 'hide']();
    setTimeout(watchInputForChanges, 100);
})();
});
</script>

<link href="cloud.css" rel="stylesheet" type="text/css" />

</head>
<body>

<div class="center1">
<form>
<input type="text" class="input1" autofocus="focus"  />
</form>
</div>

<br><br>

<div class="center1">
<div class="box">f</div>
</div>


</body>
</html>

I believe that you need to add this:

$(document).ready(function () {
    //function name does not exist outside this scope
    (function watchInputForChanges(){
        var hasInput = $('.input1').val() != "";
        $('.box')[hasInput ? 'show' : 'hide']();
        setTimeout(watchInputForChanges, 100);
    })();
});


Drav Sloan pointed out that you are missing the jQuery include as well

Apologies for not answering the direct question (simply "why doesn't this work outside of fiddle?") but I can't resist: not sure why you're polling for changes; you can bind a listener to the element. For example (in the document ready function...)

In the HTML itself:

<script src="/scripts/jquery.js"></script> <!--or wherever your script source is!!-->

Then if you're putting your scripts into tags on the same page (instead of external):

<script>
    $(document).ready(function () {
        (function() {
            $input = $('.input1');
            $box = $('.box');
            $input.on('keypress input paste', function() {
                if ($box.not(':visible') && $input.val() != "") {
                    $box.show();
                } else {
                    $box.hide();
                }
            });
        })();
    });
</script>

Catches manual entry or pasted entry.

http://jsfiddle.net/xNEZH/12/

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