为什么它在jsfiddle中有效但在我的浏览器上无效?

时间:2011-11-22 22:09:32

标签: javascript html css

请查看这个jsfiddle:

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

它在我的jsfiddle

中工作正常

[在输入中输入文本时出现的BOX]

但在我的浏览器上不起作用但是我使用的是safari,firefox和chrome的最新版本。

怎么回事?

HTML / JAVASCRIPT代码:

<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>

2 个答案:

答案 0 :(得分:1)

我相信你需要添加这个:

$(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 指出你也错过了jQuery包含

答案 1 :(得分:0)

不回答直接问题的道歉(简单地说“为什么这不能在小提琴之外工作?”)但是我无法抗拒:不确定为什么要轮询变化;您可以将侦听器绑定到该元素。例如(在文档就绪函数中......)

在HTML中:

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

然后,如果您将脚本放在同一页面上的标签上(而不是外部):

<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>

捕获手动输入或粘贴条目。

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