hasClass doesn't work in my js code?

前端 未结 2 1257
梦毁少年i
梦毁少年i 2021-01-27 23:28

I want to use hasClass in the following code, but that doesn\'t work for me, please see my demo in jsfiddle and tell me, what do I do wrong?



        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-27 23:43

    Solution

    The class is on the child, an , so add it in the jQuery selector : $('span input').

    if ($('span input').hasClass('IdRelation')) {
      alert('ok');
    }​
    

    Try the Demo.

    A bit of explanation

    Accorting to jQuery documentation, $('span input') is a descendant selector :

    Selects all elements that are descendants of a given ancestor.

    You could also use $('span > input'). It is a child selector :

    Selects all direct child elements specified by "child" of elements specified by "parent".

    Both are good in your situation, because the input is a direct child of the .

    If your code was :

    The solution will be $('div input') or $('div > form > input').

提交回复
热议问题