【问题标题】:How to use focus and blur on dynamic inserted elements? [duplicate]如何在动态插入的元素上使用焦点和模糊? [复制]
【发布时间】:2012-09-08 01:22:53
【问题描述】:

我有功能:

$(document).ready(function(){

    $("input.myclass").focus(function() {
        // something
    }).blur(function() {
        // something
    });

}

和html:

<div class="usil">
    <div class="editable">
        <form>
            <input type="text" class="myclass" />
        </form>
    </div>
</div>

在“myclass”元素上的加载页面 jquery 工作正常,但其他脚本动态添加“usil”类 div 并且在此 div 上 jquery 不起作用。怎么做?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    使用事件委托:

        $(document).on('focus',"input.myclass", function() {
            // something
        }).on('blur',"input.myclass", function() {
            // something
        });
    

    $(document).on({
        'focus': function () {
            // something
        },
        'blur': function () {
            // something
        }
    }, 'input.myclass');
    

    http://api.jquery.com/on

    http://learn.jquery.com/events/event-delegation/

    【讨论】:

    • +1 非常简单直接
    • 应该注意的是,如果可以避免使用document,通常不是一个好主意。出于性能原因,您希望使用最接近的公共静态祖先元素。
    • 是的,这值得注意——虽然我现在不打算深入讨论,因为它显然是 OP 的一个新概念,并且在典型用法上的差异是微不足道的。
    【解决方案2】:

    该代码可能会有所帮助:

    $('input').live('focus', function() {
        $('label span').text('focus');
    }).live('blur', function() {
        $('label span').text('blur');
    });
    


    使用示例: http://jsfiddle.net/CPQ37/

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    相关资源
    最近更新 更多