使用jquery从Image Title和Alt属性中删除html标记

时间:2015-04-02 18:33:13

标签: jquery html

我有一个使用CMS的客户端,标题和alt图像属性正从标题中提取。大多数标题都有html(span和br标签)。我需要从以下示例代码中删除标题和alt文本中的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>

3 个答案:

答案 0 :(得分:1)

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

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

&#13;
&#13;
var dummy = $('<p>');

$('.products img[title]').each(
   function() {
     var img = $(this);
     dummy.html( img.attr('title') );
     img.attr( 'title', dummy.text() );
   }
);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在javascript中使用replace查找br代码并将其删除:

您必须首先将ID提供给列表元素。

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

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

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

答案 2 :(得分:0)

我建议:

// 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();
});

&#13;
&#13;
$('ul li img[title]').each(function() {
  this.title = $('<div />', {
    'html': this.title
  }).text();
});
&#13;
<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>
&#13;
&#13;
&#13;

参考文献: