繁体   English   中英

使用jQuery从图像标题和Alt属性中删除HTML标签

[英]Remove html tags from Image Title and Alt attribute using jquery

我有一个使用CMS的客户端,并且标题和alt图像属性已从标题中拉出。 多数标题中都带有html(span和br标签)。 我需要从以下示例代码的标题和替代文本中删除html标签吗?

<ul class="products">
    <li><img src="images/product_image_1" title="<span>Company Name</span> First Product<br /> Name" /></li>
    <li><img src="images/product_image_2" title="<span>Company Name</span> Second Product<br /> Name" /></li>
</ul>

我需要它看起来像这样:

<ul class="products">
    <li><img src="images/product_image_1" title="Company Name First Product Name" /></li>
    <li><img src="images/product_image_2" title="Company Name Second Product Name" /></li>
</ul>

创建一个虚拟HTML元素(切勿实际添加到文档中)。

将其HTML设置为每个img title的内容,然后将标题重新设置为元素的text()内容。

 var dummy = $('<p>'); $('.products img[title]').each( function() { var img = $(this); dummy.html( img.attr('title') ); img.attr( 'title', dummy.text() ); } ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class="products"> <li><img src="images/product_image_1" title="<span>Company Name</span> First Product<br /> Name" /></li> <li><img src="images/product_image_2" title="<span>Company Name</span> Second Product<br /> Name" /></li> </ul> 

您可以在javascript中使用replace来找到br标签并将其删除:

您必须首先将id赋予列表元素。

var str = document.getElementById( 'listElement1' ).innerHTML;
var res = str.replace( '<br />', '' ); 

然后对span元素执行相同的操作。

var res = str.replace( '<span>Company Name</span>', '' ); 

我建议:

// iterate over each of the <img> elements that have a
// title attribute:
$('ul li img[title]').each(function() {
  // set the title of the current <img> to
  // the text returned from a dummy <div> element,
  // after setting its html to that of the title attribute:
  this.title = $('<div />', {
    'html': this.title
  // finding the text of that created-<div>:
  }).text();
});

 $('ul li img[title]').each(function() { this.title = $('<div />', { 'html': this.title }).text(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="products"> <li> <img src="http://lorempixel.com/200/200/nightlife" title="<span>Company Name</span> First Product<br /> Name" /> </li> <li> <img src="http://lorempixel.com/200/200/people" title="<span>Company Name</span> Second Product<br /> Name" /> </li> </ul> 

参考文献:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM