jQuery if has() selector do stuff

前端 未结 5 390
逝去的感伤
逝去的感伤 2021-01-15 05:45
  • text

http://jsfiddle.net/wZ8MC/2/

jQuery(document).ready(functi         


        
相关标签:
5条回答
  • 2021-01-15 06:12

    Check the length of your jQuery "collection":

     if (jQuery('#bad-drifting li:has(em)').length > 0) { // There is at least one element
    

    otherwise it will always be true, because what jQuery returns is always truthy.

    0 讨论(0)
  • 2021-01-15 06:27

    That's because has returns a jQuery object and an object is a truthy value in JavaScript, you should use length property:

    if (jQuery('#bad-drifting').has('em').length) {
    
    0 讨论(0)
  • 2021-01-15 06:28

    You need to check for length because jQuery('#bad-drifting li:has(em)') returns a jQuery object which will be always truthy.

    if (jQuery('#bad-drifting li:has(em)').length) { // .has('em')
    
    0 讨论(0)
  • 2021-01-15 06:28
    if (jQuery('#bad-drifting').has('em')[0]) { // do Stuff
    
    0 讨论(0)
  • 2021-01-15 06:28

    I ended up doing like this:

    if (jQuery('#bad-drifting em').length > 0) {
        console.log('we have some errors');
    }   
    
    0 讨论(0)
提交回复
热议问题