jQuery如果列表项包含'' - " 。去掉()?

时间:2017-10-17 22:00:57

标签: javascript jquery html dom

我正在重新列出李的相关文章列表,我想删除" - "标签和跨度之间没有弄乱页面上的原始内容(链接)。我必须使用jQuery,我不确定是否有一种简单的方法可以做到这一点。

<div class="related-articles card">
<h3 class="h2">
    <i class="fa fa-book text-brand-primary-dark"></i> Related Articles
</h3>

<ul>

<li>
    <a href="http://example.com/article-1">Title One</a>
            - 
    <span> Some Related Preview Text... </span>
</li>
    <li>
    <a href="http://example.com/article-2">Title Two</a>
            - 
    <span> Some Related Preview Text... </span>
</li>
    <li>
    <a href="http://example.com/article-3">Title Three</a>
            - 
    <span> Some  RelatedPreview Text... </span>
</li>
</ul>

3 个答案:

答案 0 :(得分:1)

这是我的解决方案,获取子元素并将其分配回来,因此显示的纯文本(-)将被删除!

$('.related-articles li').each(function() {
  $(this).html($(this).children());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="related-articles card">
  <h3 class="h2">
    <i class="fa fa-book text-brand-primary-dark"></i> Related Articles
  </h3>

  <ul>

    <li>
      <a href="http://example.com/article-1">Title One</a> -
      <span> Some Related Preview Text... </span>
    </li>
    <li>
      <a href="http://example.com/article-2">Title Two</a> -
      <span> Some Related Preview Text... </span>
    </li>
    <li>
      <a href="http://example.com/article-3">Title Three</a> -
      <span> Some  RelatedPreview Text... </span>
    </li>
  </ul>

答案 1 :(得分:1)

一种方法是遍历每个<li>,提取<a><span>元素并手动将它们拼接在一起,如下所示:

&#13;
&#13;
$("ul > li").each( (i, li) => {
    const $li = $(li);
    const $a = $li.find("a");
    const $span = $li.find("span");
    
    //create a temp element with just the <a> and <span>
    const $tempItem = $("<li></li>");    
    $tempItem.append( $a ).append( $span );
    //copy new HTML into old element
    $li.html( $tempItem.html () );
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>

<li>
    <a href="http://example.com/article-1">Title One</a>
            - 
    <span> Some Related Preview Text... </span>
</li>
    <li>
    <a href="http://example.com/article-2">Title Two</a>
            - 
    <span> Some Related Preview Text... </span>
</li>
    <li>
    <a href="http://example.com/article-3">Title Three</a>
            - 
    <span> Some  RelatedPreview Text... </span>
</li>
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

一个选项是:

$('.related-articles li a').map(function() {
    return this.nextSibling;
}).remove();