【问题标题】:How to write selector function in jQuery .siblings()如何在 jQuery .siblings() 中编写选择器函数
【发布时间】:2019-11-17 18:20:54
【问题描述】:

我正在尝试使用 .siblings([selector]) 方法查找所有同级元素。虽然我不确定应该如何编写选择器方法,或者我当前的选择器方法哪里出错了。

我有 html:

<div>
    <div>
        <label for="username">Username</label>
        <input class="username" type="text" placeholder="Username" id="username"/>
    </div>

    <div>
        <label for="Password">Password</label>
        <input class="password" type="password" placeholder="Password" id="password"/>
    </div>

    <div>
        <button id="login">Login</button>
    </div>
</div>

点击按钮时,如果没有输入用户名或密码字段,我想为未填充的元素添加一个类。 单击按钮时,将运行脚本:

if (username not entered) {

    jQuery(this).parent('div').siblings(function (a) {
        if (a.children('input').length > 0 && a.children('input')[0].hasClass('username'))
            return true;
        else return false;
    }).addClass('input-empty');

}

然而,这个 jQuery 调用会返回包含用户名字段的 div 和包含密码字段的 div。如果我已指定密码字段必须包含带有“用户名”类的输入标签,为什么这会返回密码字段?

【问题讨论】:

  • 您可能希望将过滤器链接到兄弟姐妹

标签: javascript jquery html jquery-selectors siblings


【解决方案1】:

the documentation

.siblings( [selector ] )

该方法接受一个参数,该参数是可选的,并且是一个选择器。

选择器
类型:选择器
一个包含选择器表达式的字符串,用于匹配元素。

如果你传递一个选择器,它必须是一个字符串

jQuery(this).parent('div').siblings(function (a) {

您正在传递一个 函数,它不是字符串。


使用the :has() psuedo-class 选择具有特定后代的元素。

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多