Global variables in jQuery
I have been working on this script:
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
$(function(){
compentecy = $('#competency_id');
$('#add_competency').bind('click', function(e){
e.preventDefault();
$.post('/script.php', {competency_id: compentecy.val(), syllabus_id: 2}, function(){
// competency = $('#competency_id');
competency.children('option[value=' + compentecy.val() + ']').remove();
});
});
});
</script>
in the $.post callback function, it seems that I can't access global variables. I tried $.competency but it didn't work. I always get a "competency is undefined" error. I had to re开发者_StackOverflow社区initialize the variable once again inside the callback. Is there a way to NOT reinitialize the variable inside the callback?
OMG. it's one of those days I guess. spelling of the variable was incorrect :P
You could use .proxy()
like this:
$.post('/script.php', {competency_id: compentecy.val(), syllabus_id: 2},
$.proxy(function(){
this.children('option[value=' + this.val() + ']').remove();
}, compentecy)
);
$.proxy()
lets your determine what this
is inside the callback, just for cases like this :)
精彩评论