【问题标题】:Why is on blur and focus not working on appended input textfield?为什么模糊和焦点不适用于附加的输入文本字段?
【发布时间】:2013-08-22 02:40:27
【问题描述】:

人。谁能向我解释为什么模糊和焦点事件不适用于附加的输入文本字段?

正如您在此 JSFIDDLE 中看到的。在 html 中创建的输入字段似乎在监听 blur 和 focus 事件。 但是,当您使用追加按钮追加输入文本字段时,输入文本字段突然不会监听模糊/焦点事件。

HTML

<input class="input" value="value 1">
<input class="input" value="value 2">
<div id="appendinput">Append a input textfield</div>
<div id="inputcontainer"></div>

jQuery

var counter = 0;

$("#appendinput").click(function () {
    $('<input class="input" value="value 3" type="text" id="input' + (counter) + '"/>').appendTo('#inputcontainer');
    counter++;
});


$('.input').on('focus', function () {
    thisValue = $(this).val();
    $(this).attr("value", "");
});
$('.input').on('blur', function () {
    if ($(this).val() === "") {
        $(this).val(thisValue);
    }
});

你能解释一下为什么这不适用于附加的输入文本字段吗? 提前谢谢你。

【问题讨论】:

    标签: jquery input focus append blur


    【解决方案1】:

    您需要使用 on 将事件委托给动态添加元素的父级。

    Live Demo

    $(document).on('focus', '.input', function () {
        thisValue = $(this).val();
        $(this).attr("value", "");
    });
    

    委托事件的优点是它们可以处理来自 以后添加到文档中的后代元素。经过 选择一个保证在该时间存在的元素 附加了委托事件处理程序,您可以使用委托事件 避免频繁附加和删除事件处理程序的需要, reference.

    【讨论】:

    • 你怎么知道的?
    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 2013-11-08
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多