jQuery 模糊事件未触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18703433/
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 blur event not firing
提问by JNYRanger
I'm new to jQuery, so I bet I'm doing something wrong, but I cannot figure out why this event is not firing. I have a textarea element that needs to have any breaking spaces removed prior to submission due to the application that is accepting the data. I am attempting to do this clean up in the textarea when it loses focus, hence the blur method. Unfortunately it does not appear to fire within my form. The weird part is the same code works in jsFiddle, but only upon the initial loss of focus. All subsequent changes to the textarea and loss of focus does not fire the event. I also read in another answer that the delegate()
or .on()
methods might need to be used, but I'm not 100% sure how to do this properly.(jQuery blur() not working?) Code is below, any advice would be helpful.
我是 jQuery 的新手,所以我敢打赌我做错了什么,但我不知道为什么这个事件没有触发。我有一个 textarea 元素,由于应用程序正在接受数据,因此需要在提交之前删除任何中断空格。当 textarea 失去焦点时,我试图在 textarea 中进行清理,因此使用了 blur 方法。不幸的是,它似乎没有在我的表单中触发。奇怪的部分是相同的代码在 jsFiddle 中工作,但仅在最初失去焦点时。对 textarea 的所有后续更改和失去焦点都不会触发该事件。我还在另一个答案中读到可能需要使用delegate()
or.on()
方法,但我不是 100% 确定如何正确执行此操作。(jQuery blur() 不起作用?)代码如下,任何建议都会有所帮助。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#comments").blur(function() {
var txt = $("#comments").html();
txt = txt.replace(/\n/g, ' ');
txt = txt.replace(/\s{3,}/g, ' ');
$("#comments").html($.trim(txt));
});
//$("#comments").trigger("blur"); added this to help fix the issue, but it didn't make a difference
});
</script>
HTML:<textarea name="comments" id="comments" style="width: 100%; height:200px"></textarea>
HTML:<textarea name="comments" id="comments" style="width: 100%; height:200px"></textarea>
And here is the jsFiddle link: http://jsfiddle.net/75JF6/17/
这是 jsFiddle 链接:http: //jsfiddle.net/75JF6/17/
EDIT: Thanks for all the fast responses. I have looked into everyone's answers and taken your advice. I'm 95% of the way there, however, there is still an issue that persists. Switching to the .val()
method instead of .html()
is a better way of doing this, but according to the jQuery API the following issue exists when calling this method on textarea
s where carriage returns are parsed out. The issue is that I need to make sure they are removed to validate the field.
编辑:感谢所有快速响应。我已经查看了每个人的答案并采纳了您的建议。我已经完成了 95%,但是,仍然存在一个问题。切换到.val()
方法而不是.html()
执行此操作的更好方法,但根据 jQuery API,textarea
在解析回车的 s 上调用此方法时存在以下问题。问题是我需要确保删除它们以验证该字段。
Note: At present, using
.val()
on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:
注意:目前,
.val()
在 textarea 元素上使用会从浏览器报告的值中去除回车符。然而,当这个值通过 XHR 发送到服务器时,回车会被保留(或由不包含在原始值中的浏览器添加)。可以使用 valHook 来解决此问题,如下所示:
$.valHooks.textarea = {
get: function( elem ) {
return elem.value.replace( /\r?\n/g, "\r\n" );
}
};
As I mentioned earlier I'm new to jQuery and could not find much information regarding how to properly use valHooks between google & stack overflow. If anyone can shed some light on this in relation to my original question it would be greatly appreciated.
正如我之前提到的,我是 jQuery 的新手,找不到关于如何在 google 和堆栈溢出之间正确使用 valHooks 的很多信息。如果有人能就我最初的问题对此有所了解,将不胜感激。
采纳答案by JNYRanger
A combination of answers from @Sushanth -- and @Eez along with some additional research brought me to the correct answer to this question. Thank you for your input, which put me on the right path. I'm going to set this answer as community wiki.
来自@Sushanth 和@Eez 的答案以及一些额外的研究使我得到了这个问题的正确答案。感谢您的投入,这使我走上了正确的道路。我将把这个答案设置为社区维基。
Both changing the retrieval method from .html()
to .val()
as well as using the .on()
function solved the issue I was experiencing. Since the form field "#comments"
was a textarea
it experienced a known issue within the jQuery API: http://api.jquery.com/val/
将检索方法从.html()
更改.val()
为 以及使用该.on()
功能都解决了我遇到的问题。由于表单字段"#comments"
是一个textarea
它在 jQuery API 中遇到了一个已知问题:http: //api.jquery.com/val/
Below is the code that actually resolved the issue:
下面是实际解决问题的代码:
$(document).ready(function () {
$.valHooks.textarea = {
get: function (elem) {
return elem.value.replace(/\r?\n/g, "<br>\n");
}
};
$("#comments").on('blur', trimText);
$("input[type='submit']").on('click', function (e) {
e.preventDefault();
trimText();
$("form:first").submit();
});
function trimText() {
var txt = $("#comments").val();
txt = txt.replace(/<br>\n/g, ' ');
txt = txt.replace(/\s{3,}/g, ' ');
//alert(txt);
$("#comments").val($.trim(txt));
}
});
I forked @Sushanth-- 's jsFiddle again to include all of this information if anyone is interested: http://jsfiddle.net/B3y4T/
如果有人感兴趣,我再次分叉 @Sushanth-- 的 jsFiddle 以包含所有这些信息:http: //jsfiddle.net/B3y4T/
回答by Sushanth --
You code is working perfectly fine.
你的代码工作得很好。
Also attach the click event on the submit button, as there is no blur event happening when you click the button. you have to explicitly make the textarea lose focus.
还要在提交按钮上附加单击事件,因为单击按钮时不会发生模糊事件。你必须明确地让 textarea 失去焦点。
$(document).ready(function () {
$("#comments").on('blur', trimText);
$("input[type='submit']").on('click', function (e) {
e.preventDefault();
trimText();
$("input[type='submit']").submit();
});
function trimText() {
var txt = $("#comments").html();
txt = txt.replace(/\n/g, ' ');
txt = txt.replace(/\s{3,}/g, ' ');
$("#comments").html($.trim(txt));
}
});
回答by mwebber
It's not required to add delegate() or on() to the element, it's only required if they are dynamically added, deleted, etc. but it won't hurt to try.
不需要向元素添加 delegate() 或 on(),只有在动态添加、删除等时才需要,但尝试一下不会有什么坏处。
For your example, replace: $("#comments").blur(function() {
With:$(document).on("blur","#comments",function() {
对于您的示例,替换: 为$("#comments").blur(function() {
:$(document).on("blur","#comments",function() {
Also, can you check thru developer tools of chrome/firefox/safari/etc if it's giving errors in the console?
另外,如果控制台中出现错误,您可以通过 chrome/firefox/safari/etc 的开发人员工具检查吗?
回答by jonesch
You were close. The on() event in jQuery is probably one of the most resource tools you have available to you, but there are few different ways to mark it up.
你很接近。jQuery 中的 on() 事件可能是您可以使用的最多的资源工具之一,但有几种不同的标记方法。
$("#comments").on({
'blur' : function() {
// your magic here
}
});
$("#comments").trigger("blur");
I forked your jsFiddle to get what you had working. http://jsfiddle.net/75JF6/33/You were close and were on the right track. Think of the on() event as adding callback functionality to any event out there. I hope that helps!
我分叉了你的 jsFiddle 来得到你的工作。http://jsfiddle.net/75JF6/33/你很接近并且走在正确的轨道上。将 on() 事件视为向任何事件添加回调功能。我希望这有帮助!
回答by Rameez
Right way: http://jsfiddle.net/75JF6/35/
正确的方法:http: //jsfiddle.net/75JF6/35/
$(document).ready(function() {
$("textarea#comments").on('blur',function() {
var txt = $(this).val();
txt.replace(/\n/g, ' ');
txt = txt.replace(/\s{3,}/g, ' ');
$(this).val($.trim(txt));
});
});
val() should be used for form input elements, textarea is no different.
val() 应该用于表单输入元素,textarea 也不例外。
回答by sudhAnsu63
Use On, delegate or Live only when you are appending the target element after the DOM ready.
仅当您在 DOM 准备好后附加目标元素时才使用 On、delegate 或 Live。
you can use keyup to do the same, except that it fires at every keystroke. The following code will fire when user is waiting for 300 ms after typing. it will be faster than the blur event.
你可以使用 keyup 来做同样的事情,除了它在每次击键时触发。当用户在输入后等待 300 毫秒时,将触发以下代码。它会比模糊事件更快。
var ClearInterValHandel;
var interval = 300 //in milisecond.
$("#comments").keyup(function(){
ClearTimeOut(ClearInterValHandel);
ClearInterValHandel = SetTimeout(trimText, interval);
});
function trimText() {
var txt = $("#comments").html();
txt = txt.replace(/\n/g, ' ');
txt = txt.replace(/\s{3,}/g, ' ');
$("#comments").html($.trim(txt));
}
回答by Kuro
It works with val()
instead of html()
它与val()
而不是html()
i think it's because html value doesnt update the actual content of DOM tree
我认为这是因为 html 值不会更新 DOM 树的实际内容
$(document).ready(function() {
$("#comments").blur(function() {
var txt = $("#comments").val();
txt = txt.replace(/\n/g, ' ');
txt = txt.replace(/\s{3,}/g, ' ');
$("#comments").val($.trim(txt));
});
});