简体   繁体   English

如何检查是否有<li>元素具有特定值

[英]How to check if an <li> element has a specific value

can i Check with JS or JQuery whether an list contains a specific Value or not?我可以使用 JS 或 JQuery 检查列表是否包含特定值?

My Code:我的代码:

HTML: HTML:

  <ul class="list-group list-group-flush" id="liste">
  </ul>

JavaScript: JavaScript:

<script type="text/javascript">
  document.getElementById('Add').onclick = function() {
    var Nutzer = document.getElementById('Suche').value;
    var Liste = document.getElementById('liste');
    if (! $("li:has(Test)")) {
      var entry = document.createElement('li');
      entry.setAttribute( 'class', 'list-group-item' );
      entry.appendChild(document.createTextNode(Nutzer));
      Liste.appendChild(entry);
    }
}
</script>

I only found Solutions with li:contains but that is not what I want.我只找到了带有 li:contains 的解决方案,但这不是我想要的。

Use Array.prototype.some on the list of li elements在 li 元素列表上使用Array.prototype.some

 console.log([...$("#liste li")].some(el => $(el).text() === "Test")); console.log([...$("#liste li")].some(el => $(el).text() === "Anything Else"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list-group list-group-flush" id="liste"> <li>Test</li> </ul>

You can do it with only vanilla JS actually...你实际上可以只用普通的 JS 来做到这一点......

Take a look:看一看:

HTML:
  <ul>
      <li>Banana</li>
      <li>Apple</li>
      <li>Test</li>
      <li>Cucumber</li>
      <li>Coconut</li>
  </ul>

JS:
  const li = document.querySelectorAll('ul li');
  for (let i = 0; i < li.length; i++) {
    // it is the same as contains
    if (/Test/g.test(li[i].textContent)) {
        console.log('I am the <li> you want', li[i])
    }
    // it is the same as equal to
    if (li[i].textContent === 'Test') {
        console.log('I am the <li> you want', li[i])
    }

  }

Cheers,干杯,

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

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