jQuery剥离HTML所有表单



我想要一个通用的.js文件,对于它在页面上遇到的每个form,在提交时,它会从所有textareainputselect元素中剥离HTML。我觉得我错过了一个基本的技巧。

$("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;");
    }
});

您没有对.find的返回值执行任何操作。this仍将引用该表单。

您可能需要考虑两件事:

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

因此:

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

演示

由于您使用的是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/

希望它能帮助

最新更新