Javascript jQuery 文本更改事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6771140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery text change event
提问by Shawn Mclean
I need to fire an event anytime the content of a textbox has changed.
每当文本框的内容发生变化时,我都需要触发一个事件。
I cant use keyupnor can I use keypress.
我不能使用keyup也不能使用keypress。
Keyup and keydown doesn't work if you hold down on the key.
如果您按住键,Keyup 和 keydown 将不起作用。
Keypress triggers before the text has actually changed. It doesn't recognize backspace or delete either.
Keypress 在文本实际更改之前触发。它也不识别退格或删除。
So now I'm assuming I'm going to have to build some custom logic or download a plugin. Are there any plugins out there? Or if I should build one, what constraints should I look out for?
所以现在我假设我将不得不构建一些自定义逻辑或下载一个插件。那里有插件吗?或者如果我应该建立一个,我应该注意什么限制?
For eg. Facebook does it with their search at the top. you can press and hold.
例如。Facebook 将他们的搜索放在顶部。你可以按住。
another example is writing a stackoverflow question. Right below the editor, the contents are copied in real time, backspace and everythng works. How do they do it?
另一个例子是写一个 stackoverflow 问题。在编辑器正下方,实时复制内容,退格和一切正常。他们是怎么做到的呢?
回答by Paul
I just took a look at SO's source. It looks like they do something a lot like this:
我只是看了一下SO的来源。看起来他们做了很多这样的事情:
function updatePreview(){
$('div').text($('textarea').val());
}
$('textarea').bind('keypress', function(){
setTimeout(updatePreview, 1);
}
);?
They do some extra stuff to make HTML tags for bold and italics and links and such and they time it. They increase the delay from 1 to longer if it takes too long to generate the HTML.
他们做了一些额外的事情来为粗体、斜体和链接等制作 HTML 标签,然后他们计时。如果生成 HTML 的时间太长,它们会将延迟从 1 增加到更长。
回答by FishBasketGordo
I had success using jQuery (in Chrome). If you hold a key down, it counts every change, not just the first one, and it counts non-print keys like backspace.
我成功地使用了 jQuery(在 Chrome 中)。如果您按住某个键,它会计算所有更改,而不仅仅是第一个,还会计算非打印键(如退格键)。
HTML
HTML
<input id="txt" type="text" />
<span id="changeCount">0</span>
JavaScript
JavaScript
$('#txt').keydown(function(event) {
// Don't count the keys which don't actually change
// the text. The four below are the arrow keys, but
// there are more that I omitted for brevity.
if (event.which != 37 && event.which != 38 &&
event.which != 39 && event.which != 40) {
// Replace the two lines below with whatever you want to
// do when the text changes.
var count = parseInt($('#changeCount').text(), 10) + 1;
$('#changeCount').text(count);
}
});
Like I said above, you'll want to filter out all of the key codes that don't change the text, like ctrl, shift, alt, enter, etc. There's also the boundary condition if you press the backspaceor deletekey when the textbox is empty or if the textbox has a maximum length and a printable key is pressed, but it's not terribly difficult to handle those either.
就像我上面说的,你要过滤掉所有的键代码不改变文本,像ctrl,shift,alt,enter,等还有边界条件如果按backspace或delete键时,文本框为空,或者文本框有一个最大长度并且按下了一个可打印的键,但处理这些也不是非常困难。
Here's a working jsfiddle example.
这是一个有效的jsfiddle 示例。
回答by pixelfreak
How about a poll? Do a setInterval
and call a function that checks the text say every 500ms? You don't want to detect content change on every key anyway because it gets kinda slow in some older browser/older computer and you would notice a lag between typing and the text displaying.
民意调查怎么样?做一个setInterval
并调用一个函数来检查文本每 500 毫秒说一次吗?无论如何,您不想检测每个键上的内容更改,因为它在某些较旧的浏览器/较旧的计算机中变得有点慢,并且您会注意到键入和显示文本之间存在延迟。
回答by rkw
You need a watcher type functionality.
你需要一个观察者类型的功能。
It resorts to setInterval polling if the other features are not available: http://james.padolsey.com/javascript/monitoring-dom-properties/
如果其他功能不可用,它会求助于 setInterval 轮询:http: //james.padolsey.com/javascript/monitoring-dom-properties/
回答by Liangliang Zheng
I have a simple solution that we use happily in one of our project.
我有一个简单的解决方案,我们可以在我们的一个项目中愉快地使用它。
you can try it @ http://jsfiddle.net/zSFdp/17/
你可以试试@http://jsfiddle.net/zSFdp/17/
var i = 0;
$('#text').bind('check_changed', function(){
var t = $(this);
// do something after certain interval, for better performance
delayRun('my_text', function(){
var pv = t.data('prev_val');
// if previous value is undefined or not equals to the current value then blablabla
if(pv == undefined || pv != t.val()){
$('#count').html(++i);
t.data('prev_val', t.val());
}
}, 1000);
})
// if the textbox is changed via typing
.keydown(function(){$(this).trigger('check_changed')})
// if the textbox is changed via 'paste' action from mouse context menu
.bind('paste', function(){$(this).trigger('check_changed')});
// clicking the flush button can force all pending functions to be run immediately
// e.g., if you want to submit the form, all delayed functions or validations should be called before submitting.
// delayRun.flush() is the method for this purpose
$('#flush').click(function(){ delayRun.flush(); });
The delayRun() function
delayRun() 函数
;(function(g){
var delayRuns = {};
var allFuncs = {};
g.delayRun = function(id, func, delay){
if(delay == undefined) delay = 200;
if(delayRuns[id] != null){
clearTimeout(delayRuns[id]);
delete delayRuns[id];
delete allFuncs[id];
}
allFuncs[id] = func;
delayRuns[id] = setTimeout(function(){
func();
delete allFuncs[id];
delete delayRuns[id];
}, delay);
};
g.delayRun.flush = function(){
for(var i in delayRuns){
if(delayRuns.hasOwnProperty(i)){
clearTimeout(delayRuns[i]);
allFuncs[i]();
delete delayRuns[i];
delete allFuncs[i];
}
}
};
})(window);
回答by Deepak Thomas
Zurb has a great plugin which might be useful for you http://www.zurb.com/playground/jquery-text-change-custom-event
Zurb 有一个很棒的插件可能对你有用 http://www.zurb.com/playground/jquery-text-change-custom-event