hasClass doesn't work in my js code?

前端 未结 2 1228
梦毁少年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 <span> child, an <input>, 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 <span>.

    If your code was :

    <div>
        <form>
            <input type="text" name="relation" class="IdRelation">
        </form>
    </div>
    

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

    0 讨论(0)
  • 2021-01-28 00:02

    It is not the <span> element that exposes the IdRelation class, but its <input> child. Try:

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

    Or maybe, depending on your actual markup:

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

    The selector in the first code snippet will match all <input> elements that are descendants of a <span> element, whereas the selector in the second snippet will match all <input> elements that are direct children of a <span> element. Both will match the <input> element in your sample markup.

    0 讨论(0)
提交回复
热议问题