2012-09-14 30 views
9

我有功能:如何在動態插入元素上使用焦點和模糊?

$(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> 

在加載頁面的jQuery的「MyClass的」元素正常工作,但其他腳本動態添加「USIL」類的div並在此div的jQuery的不要工作。怎麼做?

回答

25

使用事件代表團:

$(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/

+0

+1奈斯利簡單和直接 –

+2

應當注意的是,使用document'的'不是一般的,如果能避免這是一個好主意。出於性能原因,您想使用最接近的通用靜態祖先元素。 –

+0

是的,值得注意的是 - 雖然我剛纔不打算進入這一點,因爲這顯然是OP的一個新概念,並且典型使用的差異不明顯。從v1.9開始停用.live: – Blazemonger

-1

該代碼可以幫助:

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


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

+1

。http://stackoverflow.com/questions/14354040/jquery-1-9-live-is-not-a-function – meataxe

相關問題