将jQuery代码移动到一个函数

时间:2011-01-07 23:45:46

标签: jquery

我有以下jQuery代码:

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

我想将我的jQuery代码的内容(在'click'函数中)移动到一个单独的函数中,因为我需要在页面加载时再次调用它(在提交表单之后,以便DIV再次自动显示。)

我遇到了麻烦 - 有人可以帮忙吗?

4 个答案:

答案 0 :(得分:1)

尝试:

$('.show-additional-link').click(function() {return showAdditional(this);});

function showAdditional(e) {
    $(e).parent().next().slideDown();
    $(e).hide();
    return false;
}

并在页面上加载showAdditional($('#linkyouwantclicked'))

之类的内容

答案 1 :(得分:1)

您可以手动触发事件。这应该为处理程序保留正确的上下文,而不会有任何额外的麻烦。

jQuery(function ($) {
    // when the document has loaded
    $('.show-additional-link')
        .click(function () {    // set up the handler
            // your code here
        })
        .click()                // trigger the handler
    ;
});

答案 2 :(得分:0)

$('.show-additional-link').each(function() {makeClickable($(this));}));


function makeClickable(el) { 
    el.click(function(){
        el.parent().next().slideDown();
        el.hide();
        return false;
    });
}

答案 3 :(得分:0)

你有没有尝试过:

<script type="text/javascript">
  function showAdditional() {
    $('.show-additional-link').parent().next().slideDown();
    $('.show-additional-link').hide();
  }
</script>

并将您的show-additional-link href更改为"javascript:showAdditional()"