首页 > 解决方案 > jquery .each() 不适用于我的 div 类

问题描述

我的 html 中有一些 div,这个 js 代码在另一个文件中。找不到问题,为什么它不起作用。

$(".inputDiv").each(function () {
    $(this).focus(function () {
        $(this).css("border-bottom", "2px solid dodgerblue");  
    }).blur(function () {
        $(this).css("border-bottom", "2px solid gray");
    });
});

此文件中的其他脚本工作正常。我的html

<form method="post" th:action="@{/login}">
        <div class="inputDiv">
            <div>
                <span>login</span>
            </div>
            <input type="text" class="inputLogin dataField" name="username">
        </div>
        <div class="inputDiv">
            <div>
                <span>password</span>
            </div>
            <input type="password"  class="inputPass dataField" name="password" >
        </div>
        <input type="submit" value="Увійти" id="buttonEnter" disabled="false">
    </form>

我想在单击它时更改 div 边框底部,并在单击其他区域时将其更改回来。

标签: javascriptjquery

解决方案


您可以通过向元素添加一个tabindex属性来实现这一点inputDiv(只需在 div 内单击以设置焦点):

$(".inputDiv").focus(function() {
    $(this).css("border-bottom", "2px solid dodgerblue");
    $(this).css("outline", "none");
}).blur(function() {
    $(this).css("border-bottom", "2px solid gray");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="inputDiv" tabindex="0">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
  software like Aldus PageMaker including versions of Lorem Ipsum.
</div>


推荐阅读