【问题标题】:jquery select one class from manyjquery 从许多中选择一个类
【发布时间】:2011-02-12 07:50:41
【问题描述】:

我正在尝试实现以下功能。在一个表单中,我有多个类名为 .inputField 的字段,如果选择了其中一个字段,则与该元素关联的 div 应显示在焦点上并隐藏在模糊上。但是,当我在选择第二个元素时实现下面的代码时,该类将应用于两者。不知道我哪里错了?!?!?

html 标记:

<form class="friendlyForm" name="friendlyForm" id="friendlyForm">
                                            <ul>
                                                <li>
                                                    <label for="testField">Test field</label>
                                                    <input name="testField" value="here" class="inputField" id="testField" />
                                                    <div class="helper" style="display: none;">helper text here</div>
                                                </li>
                                                <li>
                                                    <label for="testField">Test field2</label>
                                                    <input name="testField2" value="here" class="inputField" id="testField2" />
                                                    <div class="helper" style="display: none;">helper text here</div>
                                                </li>
                                            </ul>
                                        </form>

jQuery 标记:

$('.friendlyForm').find('.inputField').each(function(i) {
    $(this).blur();
    $(this).focus(function() {
        //Add the focus class and fadeIn the helper div
        $(this).parent().addClass('focus');
        $(this).parent().parent().find('.helper').fadeIn();
    });
    $(this).blur(function () {
        //Remove the focus class and fadeOut helper div
        $(this).parent().removeClass('focus');
        $(this).parent().parent().find('.helper').fadeOut();
    });
});

这里的任何指针将不胜感激。

谢谢

【问题讨论】:

    标签: jquery jquery-selectors css-selectors


    【解决方案1】:

    如果我正确理解您的问题,这应该可以解决问题。

    $('.friendlyForm .inputField').each(function () {
      $(this).blur().focus(function () {
        $(this).parent().addClass('focus');
        $(this).siblings('.helper').fadeIn();
      }).blur(function () {
        $(this).parent().removeClass('focus');
        $(this).siblings('.helper').fadeOut();
      });
    });
    

    你做错了什么是你使用parent().parent(),它将获得&lt;ul&gt;标签,因此它会在&lt;ul&gt;中找到所有.helper元素。

    【讨论】:

    • 我实际上认为你甚至不需要.each,你可以使用$('.friendlyForm .inputField').blur().focus(...).blur(...)
    猜你喜欢
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2018-07-27
    • 1970-01-01
    相关资源
    最近更新 更多