我是 jQuery 的新手,所以我敢打赌我做错了什么,但我不知道为什么这个事件没有触发。由于接受数据的应用程序,我有一个 textarea 元素需要在提交之前删除任何分隔符。当它失去焦点时,我试图在文本区域中进行清理,因此使用了模糊方法。不幸的是,它似乎没有在我的表单中触发。奇怪的是,相同的代码在 jsFiddle 中有效,但仅在最初失去焦点时有效。文本区域的所有后续更改和失去焦点都不会触发该事件。我还在另一个答案中读到 delegate()
或 .on()
可能需要使用方法,但我不是 100% 确定如何正确执行此操作。( jQuery blur() not working? ) 代码如下,任何建议都会有所帮助。
<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>
这是 jsFiddle 链接:http://jsfiddle.net/75JF6/17/
编辑:感谢所有快速回复。我已经查看了每个人的答案并采纳了您的建议。我已经完成了 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:
$.valHooks.textarea = {
get: function( elem ) {
return elem.value.replace( /\r?\n/g, "\r\n" );
}
};
正如我之前提到的,我是 jQuery 的新手,找不到太多关于如何在 google 和堆栈溢出之间正确使用 valHooks 的信息。如果有人能就我最初的问题阐明这一点,我们将不胜感激。
最佳答案
您的代码运行良好。
还要在提交按钮上附加点击事件,因为点击按钮时不会发生模糊事件。你必须明确地让文本区域失去焦点。
$(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));
}
});
关于javascript - jQuery 模糊事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18703433/