I'd like to set a context for a function in order to limit its execution to only its inside elements.
$('#btn').live('click',function(){
$.proxy(test(),$(this).closest('div'));
});
function test(){
//doSomething
}
but the context in test() function is not the closest DIV containig my #btn button but the entire page. Could you help me开发者_如何学Python ?
$.proxy returns a function.
var mytest = function(){
// do something with `this` bound to the jquery collection to be
// created in the future sometime
}
$('#btn').live('click',function(){
// reassign mytest to a new function proxying the context through
// a relative jquery collection
mytest = $.proxy(mytest,$(this).closest('div'));
});
This is kind of weird and clumsy, but it should do what you're thinking. There a good chance of running into async issues because the proxy happens on the click. Without knowing the specifics of your problem I don't know if using proxy is what you need.
Changing test()
to test
doesn't seem to make a difference, strange how that's not working -- but after reading the comments on the jQuery page for .proxy
-- it seems it's plagued with problems and inconsistencies. I would use something along these lines:
HTML
<div>hello</div>
jQuery
function test()
{
alert($(this).html()); // Will alert hello
}
$(document).ready(function() {
test.call($('div').get(0)); // I use .get() so only the DOM object is passed.
// That makes it more consistent with how jQuery
// passes objects to .each, etc.
})
Fiddle: http://jsfiddle.net/u8x22/
精彩评论