jQuery - how to pass $(this) as an object?
I'm trying to pass an object into a function but think there's a problem with $(this) not actually being valid at the point of passing it in.
$('textarea[name*=quote]').live('bind',function(){
}).limit('10',$(this).parents('form').children().find('span[name*=qc]') );
The second parameter can be either a string or an object like $('span#qc'), but I also want to be able to pass in an object which references the current one.
Why? Because I have several forms 开发者_运维知识库on same page, each containing textarea#quote, so depending on which form is selected I want to be able to reference a particular element within the same form.
Anyone??
You need to make a separate call for each individual instance using .each
, like this:
$('textarea#quote').each(function() {
$(this).live('bind',function(){
}).limit('10',$(this).parents('form').children().find('span#qc') );
});
To bind all of them with access to $(this)
, use .each()
, like this:
$('textarea[name*=quote]').each(function() {
$(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
});
If you want .live()
-like functionality on the second part, you need to either use .livequery()
, like this:
$('textarea[name*=quote]').livequery(function() {
$(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
});
Or alternatively, bind them like the first example and also bind when loading new elements, e.g. if you're using $.ajax()
, it would look like this:
$.ajax({
url: blah.html
success: function(data) {
//do something with data
$('textarea[name*=quote]', data).each(function() {
$(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
});
}
});
The key here is , data
, it provides a context to search in, so this is only executing on elements found in the returned data. You can also wrap this in a function to prevent duplication of code, like this:
function bindStuff(context) {
$('textarea[name*=quote]', context || document).each(function() {
$(this).limit('10',$(this).closest('form').find('span[name*=qc]'));
});
}
In document.ready
, call bindStuff(document)
, in $.ajax
, you'd call bindStuff(data)
.
精彩评论