[英]Using substring with text() to remove html tags?
I'm using jQueryUI autocomplete to pull results from a SQL database. 我正在使用jQueryUI自动完成功能从SQL数据库中提取结果。 I use the
substring
method to limit results' descriptions to 350 characters. 我使用
substring
方法将结果的描述限制为350个字符。 But it seems that I can't use .text()
alongside with substring to remove all the html tags from the descriptions. 但似乎我不能与子字符串一起使用
.text()
来删除描述中的所有html标记。 When I type in a search term, the console returns 当我输入搜索词时,控制台会返回
TypeError: item.description.text is not a function
Can someone tell me what should be used to remove html tags from descriptions? 有人可以告诉我从说明中删除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.
}
Assigning the Data: 分配数据:
}).data("ui-autocomplete")._renderItem = function(ul, item) {
var inner_html = '..........<p>'+ item.description +'...</div></div></a>';
The problem is that .text()
is a method of jQuery objects (which contain nodes), and .textContent
is a property of nodes. 问题在于
.text()
是jQuery对象(包含节点)的方法,而.textContent
是节点的属性。 Instead, it seems that item.description
is a string. 相反,似乎
item.description
是字符串。
Then, you could create a DOM element with the string as its html, and then use .textContent
or .text()
. 然后,您可以使用字符串作为html创建一个DOM元素,然后使用
.textContent
或.text()
。 But that is a vulnerable practice: 但这是一种脆弱的做法:
$('<img src="//" onerror=alert("hacked!") />');
The safe way is: 安全的方法是:
function stripHTML(html) {
var sandbox = document.implementation.createHTMLDocument().body;
sandbox.innerHTML = html;
return sandbox.textContent;
}
/* ... */
description: stripHTML(item.description).substring(0,350);
/* ... */
Note document.implementation.createHTMLDocument
doesn't work on old browsers. 注意
document.implementation.createHTMLDocument
在旧的浏览器上不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.