[英]Using substring with text() to remove html tags?
我正在使用jQueryUI自动完成功能从SQL数据库中提取结果。 我使用substring
方法将结果的描述限制为350个字符。 但似乎我不能与子字符串一起使用.text()
来删除描述中的所有html标记。 当我输入搜索词时,控制台会返回
TypeError: item.description.text is not a function
有人可以告诉我从说明中删除html标签的方法吗?
$(function() {
$( "#Search" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "get.php",
dataType:"json",
data:{q:request.term},
success: function( data ) {
response($.map( data.products, function( item ) { return {
label:item.name,
category:item.category,
description:item.description.text().substring(0,350).split(" ").slice(0, -1).join(" ")
//.text() doesn't work.
}
分配数据:
}).data("ui-autocomplete")._renderItem = function(ul, item) {
var inner_html = '..........<p>'+ item.description +'...</div></div></a>';
问题在于.text()
是jQuery对象(包含节点)的方法,而.textContent
是节点的属性。 相反,似乎item.description
是字符串。
然后,您可以使用字符串作为html创建一个DOM元素,然后使用.textContent
或.text()
。 但这是一种脆弱的做法:
$('<img src="//" onerror=alert("hacked!") />');
安全的方法是:
function stripHTML(html) {
var sandbox = document.implementation.createHTMLDocument().body;
sandbox.innerHTML = html;
return sandbox.textContent;
}
/* ... */
description: stripHTML(item.description).substring(0,350);
/* ... */
注意document.implementation.createHTMLDocument
在旧的浏览器上不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.