move jQuery code to a function
I have the following jQuery code:
$('.show-additional-link').click(function(){
$(this).parent().next().slideDown();
$(this).hide();
return false;
});
HTML:
<div class="row">
<label for="native_language">Select</label>
<select name="native_language" id="native_language">
<option value="">Any</option>
<option value="1">English</option>
</select>
<a class="show-additional-link" href="#">Select Additional Languages</a>
</div>
<div id="additional-languages" style="display: none;">
<div class="row">
<!-- additional language checkboxes -->
</div>
</div>
I would like to move the contents of my jQuery code (within the 'click' function) in to a separa开发者_如何转开发te function, as I will need to call it again on page load (after the form is submitted, so that the DIV is shown again automatically).
I'm having trouble with this - can anyone help?
try:
$('.show-additional-link').click(function() {return showAdditional(this);});
function showAdditional(e) {
$(e).parent().next().slideDown();
$(e).hide();
return false;
}
and on page load something like showAdditional($('#linkyouwantclicked'))
You can manually trigger events. This should keep the right context for the handlers without any extra hassles.
jQuery(function ($) {
// when the document has loaded
$('.show-additional-link')
.click(function () { // set up the handler
// your code here
})
.click() // trigger the handler
;
});
$('.show-additional-link').each(function() {makeClickable($(this));}));
function makeClickable(el) {
el.click(function(){
el.parent().next().slideDown();
el.hide();
return false;
});
}
Did you try:
<script type="text/javascript">
function showAdditional() {
$('.show-additional-link').parent().next().slideDown();
$('.show-additional-link').hide();
}
</script>
and change your show-additional-link href to "javascript:showAdditional()"
?
精彩评论