【问题标题】:trying to set focus of dynamically added input试图设置动态添加输入的焦点
【发布时间】:2016-12-09 22:20:29
【问题描述】:

我正忙着让这个输入成为焦点。它是动态加载的。在输入模糊时,它应该进行一些检查,然后如果输入了不正确的 id,则返回该输入。 $(itemID) 是我想要关注的。

这是我在页面加载时调用的 javascript 函数。

function addBlurEvent() {
            $("#brochureItems").on("blur", ".item-ID", (function (e) {
                var itemID = $(this);
                var itemIDVal = $.trim($(this).val());               

                if (itemIDVal != "") {
                    var item = "";
                    $.each(window.listOfItems, function(i, v) {
                        if (v.No.search(itemIDVal) != -1) {
                            item = v.Description;
                            return;
                        }
                    });
                    if(item != "") {
                        $(itemID).parent().parent().siblings(".item-desc").find("input").first().val(item);
                        $(itemID).parent().siblings(":last").find("input").first().focus();
                    } else {
                        slideDownMsg("Item: " + itemIDVal + " not found.");
                        slideUpMsg(3000);
                        $(itemID).focus();
                    }

                } else {
                    $(itemID).parent().siblings(".item-desc").find("input").first().val("");
                    $(itemID).parent().siblings(":last").find("input").val("")
                }
            }));
            $(".removeRow").on('click', function() {
                $(this).closest("tr").remove();
            });
        }

这是动态添加的表格:

<table class="table table-bordered table-striped" id="brochureItems">
<thead>
    <tr>
        <th>
            Item Code
        </th>
        <th>
            Brochure Code
        </th>
        <th width="35%">
            Item Description
        </th>
        <th>
            Retail
        </th>
        <th>
            Remove
        </th>
    </tr>
</thead>
<tbody>

    <tr>
        <td class="row">
            <div class="col-md-8">
                <input id="brochureItems_0__itemNo" class="form-control text-box single-line valid item-ID" data-val="true" data-val-required="The Item Code field is required." name="brochureItems[0].itemNo" aria-invalid="false" type="text">
            </div>
        </td>
        <td class="row">
            <div class="col-md-8">
                <input id="brochureItems_0__brocCode" class="form-control text-box single-line" data-val="true" data-val-required="The Brochure Code field is required." name="brochureItems[0].brocCode" type="text">
            </div>
        </td>
        <td class="row item-desc">
            <div class="col-md-12">
                <input id="brochureItems_0__itemDesc" class="form-control text-box single-line" data-val="true" data-val-required="The Item Description field is required." name="brochureItems[0].itemDesc" readonly="readonly" tabindex="-1" onfocus="this.blur()" type="text">
            </div>
        </td>
        <td class="row">
            <div class="col-md-8">
                <input id="brochureItems_0__retail" class="form-control text-box single-line" data-val="true" data-val-number="The field Retail must be a number." data-val-required="The Retail field is required." name="brochureItems[0].retail" type="text">
            </div>
        </td>
        <td class="remove"><span class="glyphicon glyphicon-remove removeRow"></span></td>
    </tr>
</tbody>

我只能在检查器中看到。源代码显示了一个空的 div 表应该去的地方。

我认为这并不重要,但是 addBlurEvent 函数在 ajax 调用成功时被调用。这是第一个被调用的函数:

function loadItems() {
            $.ajax({
                url: '@Url.Action("_BrochureItems", "Brochure")',
                type: 'POST',
                data: { model: @Html.Raw(Json.Encode(@Model.brochureItems)) },
                success: function (results) {
                    $("#itemList").html(results);
                    addBlurEvent();
                },
                error: function (request, status, error) {
                    displayError("Error", request.responseText);
                }
            });
        }

【问题讨论】:

  • 事件仅添加到 DOM 中当前存在的元素中。您需要将事件应用于在初始页面加载后动态创建的每个输入。
  • 但是在动态添加项目后页面加载时调用此函数
  • 您可以在问题中包含html 吗?注意itemID 被定义为var itemID = $(this) 处的jQuery 对象,不需要再以itemID 作为参数调用jQuery()
  • 所以,有一件事:你将一个 jQuery 对象包装在一个 jQuery 对象中,这有点奇怪。 itemID 已经是一个 jQuery 对象,所以你不需要做 $(itemID).focus(),你可以做 itemID.focus()。这样做没什么大不了的,只是看起来很有趣。您拥有的代码应该可以工作,除非该元素不存在或被禁用。检查您的控制台是否有任何错误。
  • onfocus="this.blur()" 的目的是什么?

标签: javascript jquery


【解决方案1】:

终于想通了。我认为必须有一种方法,因为我在该函数中的其他事件正在工作,而不是那个焦点事件。最终找到了解决我的问题的这个 SO Q&A:jquery focus back to the same input field on error not working on all browsers

基本上,我必须在焦点上设置超时。所以这是执行此操作的代码:

setTimeout(function() { itemID.focus(); }, 50);

【讨论】:

    【解决方案2】:

    删除函数周围的()

    siblings 的问题我做了假设

    有些代码没用,我把它注释掉了。 您的示例中“不存在”某些代码,因此我注释掉了对它的引用。

    我做了一些假设,您希望将“单元格”集中在“td”引用的同一 TD 行中,并带有 .row 类。

    function addBlurEvent() {
      $("#brochureItems").on("blur", ".item-ID", function(e) {
        var itemID = $(this);
        var itemIDVal = $.trim(itemID.val());
    
        if (itemIDVal != "") {
          var item = "";
          /* $.each(window.listOfItems, function(i, v) {
             if (v.No.search(itemIDVal) != -1) {
               item = v.Description;
               return;
             }
           });
           */
          if (item != "") {
            // only one input in a cell (td)
            // itemID.parent('.row').siblings(".item-desc").find("input").first().val(item);
            itemID.parent('.row').siblings(".item-desc").find("input").val(item);
            // no siblings of the inputs parent div exist in the TD cell
            itemID.parent('.row').siblings(":last").find("input").first().focus();
          } else {
            //slideDownMsg("Item: " + itemIDVal + " not found.");
            //slideUpMsg(3000);
            itemID.focus();
          }
    
        } else {
          itemID.parent('.row').siblings(".item-desc").find("input").val("");
          itemID.parent('.row').siblings().last().find("input").val("")
        }
      });
      $(".removeRow").on('click', function() {
        $(this).closest("tr").remove();
      });
    }
    

    参考小提琴:https://jsfiddle.net/xL8wh3qo/

    查看这个更新的小提琴,我在其中展示了如何保存表行、克隆它然后允许您从中添加新行到表中的示例。即使删除了所有行,您也可以从保存的克隆中添加一个新行,并根据您的原始行使用正确的 id:https://jsfiddle.net/DTcHh/27778/

    【讨论】:

    • 去掉()是什么函数?小提琴也不专注于模糊上的.item-ID
    • 我在添加或删除行时没有任何问题。你读过我的问题吗?
    • 是的,您是否查看了实际的焦点代码,基本上您的选择器是/不是用于元素。另请注意,您可以将事件处理程序挂钩放在插入表格的元素上,以避免在获取数据时这样做;就像我链接到的例子一样。我只包括第二个例子来说明如何做到这一点。
    • 注意关于第一个问题$("#brochureItems").on("blur", ".item-ID", (function (e) { 看到( 就在函数之前?
    • 还要注意,“插入行”也是为了证明事件处理程序被挂在行之外,因此新行(如果您以这种方式插入)将继承事件处理程序而无需重新附加到新元素,即新行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2018-12-30
    • 2013-11-01
    • 1970-01-01
    相关资源
    最近更新 更多