找到子 H3 并检查是否有值

我希望用来jQuery查看一堆<div>具有相同类名的元素,并检查h3这些<div>元素中是否有任何内容。我在想这会起作用(如下所示),但它不是......我做错了什么?


$('.wrapperDIV').each(function (i) {

    if( $(this).closest('h3').val().length == 0 ) {

        $(this).addClass('.hideME');

    }

});

标记是:


<div class="wrapperDIV">

  <span class="ItemNo">5.</span>

     <a href="#" title="Read more about "><img src="" title="" alt=""></a>

        <h3></h3>

        <div class="composer-button">

        <a href="#" class="read-more" title="Read more about ">Read more</a>

    </div>

</div>


吃鸡游戏
浏览 121回答 3
3回答

PIPIONE

您可以通过使用:empty伪类单独使用 CSS 来实现此效果:.wrapperDIV h3:empty {&nbsp; display: none;}延伸阅读:https://developer.mozilla.org/en-US/docs/Web/CSS/:empty

四季花海

尝试使用获取文本而不是值$('.wrapperDIV').each(function (i) {&nbsp; &nbsp;if( $(this).find('h3').text() === "" ) {&nbsp; &nbsp; &nbsp; $(this).addClass('.hideME');&nbsp; &nbsp;}});<div class="wrapperDIV">&nbsp; &nbsp; <span class="ItemNo">5.</span>&nbsp; &nbsp; <a href="#" title="Read more about "><img src="" title="" alt=""></a>&nbsp; &nbsp; <h3></h3>&nbsp; &nbsp; <div class="composer-button"><a href="#" class="read-more" title="Read more about ">Read more</a></div></div>

德玛西亚99

你可以在 vanilla JavaScript 中尝试这个可行的代码:<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <title>test1</title>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; window.onload = function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let div = document.getElementsByClassName('wrapperDIV');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let ch = div[0].children;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(let i=0;i<ch.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ( ch[i].tagName=='H3' ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let text = ch[i].textContent;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!text) console.log('It\'s h3 without text')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></head><body>&nbsp; &nbsp; <div class="wrapperDIV">&nbsp; &nbsp; &nbsp; &nbsp; <span class="ItemNo">5.</span>&nbsp; &nbsp; &nbsp; &nbsp; <a href="#" title="Read more about "><img src="" title="" alt=""></a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h3></h3>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="composer-button">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href="#" class="read-more" title="Read more about ">Read more</a>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></body></html>在 jQuery 中,您可以使用如下代码:&nbsp; &nbsp; $(document).ready(function(){&nbsp; &nbsp; &nbsp; &nbsp; let h3 = $(".wrapperDIV > h3");&nbsp; &nbsp; &nbsp; &nbsp; if ( !h3.textContent ) console.log('h3 has no text contents');&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript