我正在工作的文本字段,这是按“回车”按钮,但不幸的是,它不工作。我正在尝试跟踪我的项目中的代码。
这是我的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();" />我希望我能得到你们的帮助。在进阶时谢谢。
发布于 2014-05-27 12:38:57
使用唯一的选择器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
发布于 2014-05-27 12:47:50
将$("input[type=text]").on...放在$(document).ready中,如果您想使用JQuery,请确保您使用的是live 1.7之前的版本
发布于 2014-05-27 13:07:16
将您的html更改为
<form onsubmit="doSomething();" >
<input type="text" id="search">
<input type="submit" id="btnSearch" />
</form>使用此函数时,您不必监听enter键事件,您的doSomething()函数将在输入字段中按enter键时自动调用
DEMO
https://stackoverflow.com/questions/23881104
复制相似问题