2015-11-06 56 views
1

我想要一个通用的.js文件,它对于在页面上遇到的每个form在提交时都会从所有textarea,inputselect元素中去除HTML。我觉得我错过了一个基本的技巧。jQuery strip HTML all forms

$("form").each(function() { 
    $(this).find(':input') 
    if (!isNaN(this.value)) { 
     this.value = this.value 
      .replace(/&/g, "&") 
      .replace(/</g, "&lt;") 
      .replace(/>/g, "&gt;") 
      .replace(/"/g, "&quot;") 
      .replace(/'/g, "&#039;"); 
    } 
}); 
+0

尽管知道HTML注入是一件好事,但我会做这个服务器端以及它会更安全。绕过任何JS输入验证是微不足道的。 –

+0

服务器端已经占了。这纯粹是为了给出更优雅的错误信息。 – jacob21

+0

好消息,继续:D –

回答

3

你没有做任何事情,从.find返回值。 this仍然会参考表格。你可能想

两件事情要考虑:

  • 使用后代组合子立即访问字段:$('form :input')
  • val二传手处理迭代本身

这样:

$('form :input').val(function() { 
    return !isNaN(this.value) ? this.value : this.value.replace(...); 
}); 

Demo

+1

@ T.J.Crowder:很对!谢谢 –

+0

使用'val'的回调很好,因此经常被忽略(包括我)。 –

+0

这很美。 – jacob21

0

由于您使用jQuery,你可以让它为你做的编码:

function htmlEncode(value){ 
    //create a in-memory div, set it's inner text(which jQuery automatically encodes) 
    //then grab the encoded contents back out. The div never exists on the page. 
    return $('<div/>').text(value).html(); 
} 

function htmlDecode(value){ 
    return $('<div/>').html(value).text(); 
} 

然后做:

$('form :input').val(function() { 
    return this.value = htmlEncode(this.value); 
}); 

启发:https://stackoverflow.com/a/1219983/5528759

看到一个演示在这里http://jsfiddle.net/vbwt3828/

希望它有帮助