gpt4 book ai didi

javascript - 使用带有 text() 的子字符串来删除 html 标签?

转载 作者:行者123 更新时间:2023-11-28 19:56:17 24 4
gpt4 key购买 nike

我正在使用 jQueryUI 自动完成从 SQL 数据库中提取结果。我使用 substring 方法将结果描述限制为 350 个字符。但似乎我无法将 .text() 与子字符串一起使用来从描述中删除所有 html 标签。当我输入搜索词时,控制台返回

类型错误:item.description.text 不是函数

有人可以告诉我应该使用什么来从描述中删除 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在旧浏览器上不起作用。

关于javascript - 使用带有 text() 的子字符串来删除 html 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22488851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com