一千萬個為什麽

搜索

JavaScript - 檢測HTML

我有一個HTML textarea元素。我想阻止用戶在此區域中輸入任何HTML標記。如何檢測用戶是否使用JavaScript輸入任何HTML textarea?

謝謝

最佳答案

One of the ways is to let the keypress event return false when the pressed key matches < or >. To distinguish real HTML tags from innocent "lesser than" and "greater than" signs, you may need to put some regex in. And since you can't parse HTML reliably with regex... There's however a jQuery way:

var sanitized = $('<div>').html(textareavalue).text();

The normal practice is however to just let the client enter whatever it want and sanitize HTML during display by the server side view technology in question. How to do it depends on the view technology you're using. In for example PHP you can use htmlspecialchars() for this and in JSP/JSTL the fn:escapeXml(). This is more robust since Javascript can be disabled/hacked/spoofed by the client.

轉載註明原文: JavaScript - 檢測HTML