簡體   English   中英

在text()中使用子字符串來刪除html標簽?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM