Jquery文本输入变化函数不起作用

3

我只是使用PHP的GET方法获取参数,然后使用jQuery使用它们。运行页面时没有输出。

<?php
    if (isset($_GET['url'])){
        $url = $_GET['url'];
        $url = explode(" " , $url);
        echo end($url);
        exit;
    }
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $('input[type=text]').change(function (){
        if ($(this).val() !== ''){
            var url = $(this).val():
            $.post('grab.php?url='+url+'', function (data){
                window.open(data, 'Download', 'width=10,height=10');
                $(this).html('');
            });
        }
    });
</script>
</head>
<body>
<input type="text" style="width:100%;height:20px;"/>
</body>
</html>

我刚开始学设计,希望我的错误能够被发现。
3个回答

1
首先,将您的文档放入标准模式(通过在开头使用适当的doctype,这意味着HTML 4 / XHTML 1严格或HTML 5)。 然后,您可以使用错误控制台进行调试。
我找到了以下错误。
Unexpected token: ':' on line 7,

冒号应该是分号。

var url = $(this).val():

然后,为什么没有任何事情发生的实际原因是在调用/缓存脚本时输入不存在。您需要在DOM构建完成后执行它。

$(document).ready(function() {
   // content
});

最终代码。

$(document).ready(function() {
   $('input[type=text]').change(function (){
      if ($(this).val() !== ''){
         var url = $(this).val();
         $.post('grab.php?url='+url+'', function (data){
            window.open(data, 'Download', 'width=10,height=10');
            $(this).html('');
         });
      }
   });   
});

0
将它放在 $(document).ready() 中,像这样:
$(document).ready(function() {
    $('input[type=text]').change(function (){
        if ($(this).val() !== ''){
            var url = $(this).val():
            $.post('grab.php?url='+url+'', function (data){
                window.open(data, 'Download', 'width=10,height=10');
                $(this).html('');
            });
        }
    });
});

0

我认为在文本输入框上使用.change事件并不可取。通常情况下,.blur和.focus更加合适。

$(document).ready(function() {
$('input[type=text]').blur(function(){
    var currentInput = this;
    if ($(currentInput ).val() != ''){
        var url = $(currentInput ).val();
        $.post('grab.php?url='+url, function(data){
            window.open(data, 'Download', 'width=10,height=10');
            $(currentInput).val('');
        });
    }
});
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接