为什么javascript按下输入按钮没有功能?

时间:2014-05-27 04:30:45

标签: javascript jquery html

我正在处理一个可以使用“输入”按钮按下的文本字段,但不幸的是它不起作用。我正在尝试在我的项目中使用代码。

这是我的JavaScript代码:

<script>
$(document).ready(function() {  
    // Live Search
    // On Search Submit and Get Results
    function search() {
        var query_value = $('input#search').val();
        $('b#search-string').html(query_value);
        if(query_value !== ''){
            $.ajax({
                type: "POST",
                url: "search.php",
                data: { query: query_value },
                cache: false,
                success: function(html){
                    $("ul#results").html(html);
                }
            });
        }
            return false;    
    }

    $("input#search").live("keyup", function(e) {
        var theSearch = $('#search');
        // Set Timeout
        clearTimeout($.data(this, 'timer'));

        // Set Search String
        var search_string = $(this).val();

        // Do Search
        if (search_string == '') {
            $("ul#results").fadeOut();
            $('h4#results-text').fadeOut();
        }else{
            $("ul#results").fadeIn();
            $('h4#results-text').fadeIn();
            $(this).data('timer', setTimeout(search, 0));
        };
    });

});

    $("#search").on('keyup',function(e){
    var text = document.getElementById("search").value;
    if(text !== ""){
        if (e.which == 13){
            $("#btnSearch").click();
        }
    }   
});

function doSomething(){
    var text = document.getElementById("search").value;
    window.location.assign("search.php?value = " + text);
}
});

</script>

这是我的HTML代码:

<input type="text" id="search">
<input type="button" id="btnSearch" onclick="doSomething();" />

我希望我会得到你们的帮助。谢谢你提前。

3 个答案:

答案 0 :(得分:2)

使用唯一选择器ID

$("#search").on('keyup',function(e){

    if (e.which == 13){
        alert('abc');
    }
});

demo jsfiddle

使用input type选择器

$('input[type=text]').each(function(i,e) {

    $("#"+e.id).on('keyup',function(e){

        if (e.which == 13){
            alert('abc');
        }
    });
});

another demo

答案 1 :(得分:1)

$("input[type=text]").on...放在$(document).ready内,并确保在1.7之前使用JQuery版本如果您想使用live

答案 2 :(得分:0)

将您的HTML更改为

  <form onsubmit="doSomething();" >
   <input type="text" id="search">
   <input type="submit" id="btnSearch"  />
  </form>

使用它时你不必听输入键事件你的doSomething()函数会在输入字段输入时自动调用

DEMO