jQuery keyup()非法字符 [英] jQuery keyup() illegal characters

查看:89
本文介绍了jQuery keyup()非法字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字段,想要在显示用户键入的内容时防止出现一些非法字符. 如何在以下示例中做到这一点?

I have a field and want to prevent some illegal characters while showing the user as he types. How can I do this in follow example?

  $('input').bind("change keyup", function() {
   var val = $(this).attr("value");
   /*
   if (val --contains-- '"') {
    $(this).css("background", "red");
           val = val.replace('"', "");
              $(this).attr("value", val)
   }
   */
   $("p").html(val);
  });

我应该将非法字符放入数组中

I should put the illegal characters in an array

var vowels = new Array('"', "<", ">", "&");

推荐答案

尝试使用正则表达式.

$('input').bind("change keyup", function() {
 var val = $(this).val();
 var regex = /["<>&]/g;
 if (val.match(regex)) {
   $(this).css("background", "red");
   val = val.replace(regex, "");
   $(this).val(val);
 }
 $("p").html(val);
});

还有,仅供参考:您可以将.attr("value",val)替换为.val(val),将.attr("value")替换为.val()

And FYI: you can replace .attr("value",val) with .val(val) and .attr("value") with .val()

更新:

如果要排除更多字符,可以将它们放入正则表达式中.如果要排除用于控制正则表达式的字符,则需要使用\字符对它们进行转义,以控制正则表达式为:[]()/\+{}?*+.^$

If you want to exclude more characters you can just put them into the regex. If you want to exclude an character that is used to control the regex you need to escape them with \ characters to control the regex are: []()/\+{}?*+.^$

这篇关于jQuery keyup()非法字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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