如何在每次使用JQuery在输入字段中更改内容时执行函数? [英] How to execute a function every time the content is changed in an input field using JQuery?

查看:84
本文介绍了如何在每次使用JQuery在输入字段中更改内容时执行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段< input type =textid =search/> 我希望每次用户都执行一个JavaScript函数改变其中的内容(逐字母)。我怎么能用jQuery做到这一点?

I have a text field <input type="text" id="search" /> and I would like to execute a JavaScript function every time the user change the content in it (letter by letter). How can I do this using jQuery?

我试图将这个函数作为使用JQuery,你如何检测是否有值当字段仍有焦点时,文本输入已更改?但我没有任何反应。

I tried to implement the function as the answer to Using JQuery, how do you detect if the value of a text input has changed while the field still has focus? but nothing happens for me.

这是我的HTML:

<html>
<head>
<script type="text/javascript" src="/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="/search.js"></script>
</head> 
<body> 
<form>
<input type="text" name="search" id="search" /> 
</form>
</body> 
</html>

我的search.js是:

My search.js is:

var target = $('#search'), val = target.val();

function search()
{
    alert('search');
}

target.keyup(search);

我也试过(没有任何反应):

I have also tried with (nothing happens):

$('input[name=search]').change(function() {
    alert('changed');
})

如果我尝试使用jQuery添加一些HTML,它可以工作:

And if I try just adding some HTML using jQuery, it works:

$(function(){
    $("<p>hello</p>").insertAfter("#search");
})


推荐答案

更改事件不会触发直到控件失去焦点。如果您只对文本感兴趣,可以使用 .keypress()在内容更改之前执行某些操作或者 .keyup()以后再做一些事情。

The change event doesn't fire until the control loses focus. If you are only interested in text, you can use .keypress() to do something before the contents change, or .keyup() to do something afterwards.

以下是在jsfiddle中使用keypress的示例: http://jsfiddle.net/R6vmZ/

Here is an example using keypress in jsfiddle: http://jsfiddle.net/R6vmZ/

这篇关于如何在每次使用JQuery在输入字段中更改内容时执行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆