在< input>中删除HTML标签.在按键上 [英] Remove HTML tags in <input> on keypress

查看:190
本文介绍了在< input>中删除HTML标签.在按键上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个代码,并且可以通过jQuery删除<input>中的HTML标记,效果很好

I made a code and it's working fine to remove HTML tags in <input> by jQuery

$("input").on("keypress",function(e){
    var val = $(this).val();
    var open = val.indexOf('<');
    var close = val.indexOf('>');
    if(open!==-1 && close!==-1) {
      $(this).val(val.replace(val.slice(open,close+1),""));
    }
});

演示: http://jsbin.com/uzibey/1/edit

但是我应该使用任何更好的主意或功能吗?

But any better idea or functions should I use ?

PS:不需要服务器端安全,请在管理"区域中使用.

PS : No server side security needed , Using in Admin area btw.

推荐答案

您还可以使用DOM清理您的输入.只需创建一个虚拟元素(不将其插入文档中),然后使用innerHTML插入输入的值即可.然后删除除文本节点以外的所有节点.

You can also use the DOM to sanitise your input. Simply create a dummy element (without inserting it into the document) and insert the value of the input using innerHTML. Then remove all nodes except text nodes.

这样做的好处是可以使用实际的HTML解析器来检测HTML,而不是使用正则表达式近似值.浏览器可以解释为HTML元素的所有内容都将被删除.

This has the benefit of using an actual HTML parser to detect HTML, instead of a regex approximation. Anything that can be interpreted as an HTML element by the browser will be removed.

这是一个非常基本的演示: http://jsfiddle.net/uA94h/

Here is a very basic demonstration: http://jsfiddle.net/uA94h/

上面的演示完全删除了非文本节点.根据要求,下面是一个演示,其中元素替换为文本: http://jsfiddle.net/TknBs/.

The above demonstration removes non-text nodes entirely. By request, here is a demonstration where elements are replaced with their text: http://jsfiddle.net/TknBs/.

这篇关于在&lt; input&gt;中删除HTML标签.在按键上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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