首页 文章

如何检查div是否与jQuery中的另一个div具有相同的文本

提问于
浏览
-4

我无法检查div是否与jQuery中的另一个div具有相同的文本

这就是我的意思

if div1 has the text hi and div2 also has hi then div2 should be removed

这是我的代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Duplicated div should be removed -->

<div>Java</div>
<div>C#</div>
<div>Python</div>
<div>Java</div>

谢谢,

Arnav

3 回答

  • 1

    您只需执行以下操作即可 Build 此功能

    var itemsFound = [];
    $("div.item").each(function(index) {
    	if(itemsFound.indexOf($(this).text()) > -1) {
      	$(this).remove()
      } else {
    	  itemsFound.push($(this).text());
      }
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="item">Java</div>
    <div class="item">C#</div>
    <div class="item">Python</div>
    <div class="item" value="abc">Java</div>
    
  • 3

    你可以试试这个:

    let arrayItems = [];
    let arrayNames = [];
    $('div').each(function(e){
       if(!arrayNames.includes($(this).text())){
          arrayNames.push($(this).text());
          arrayItems.push(this);
       }
    });
    

    你可以看到 console.log 的结果将有三个项目

    console.log(arrayItems,arrayNames);

  • 1

    您可以使用简单的 reduce

    $(() => {
      [...$('div')].reduce(
        (a, e) => {
          if (a[e.textContent]) e.replaceWith('')
          else a[e.textContent] = !0
          return a
        }, {}
      );
    });
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- Duplicated div should be removed -->
    
    <div>Java</div>
    <div>C#</div>
    <div>Python</div>
    <div>Java</div>
    

相关问题