开发者

jQuery change events on docready

I want to run part of a function when the page initially loads, but the majority of the change event should only run when the target is then subsequently interacted with.

The problem is that the two events are not unrelated - on page load I want to show certain divs, and then I want a click action that shows/hides the divs. I can get these two parts to run separately, but haven't been able to combine them.

My question is, what is the best way to achieve this separation? Is there a method in jQuery that says 'only run this part once' or 'run this part on page loa开发者_如何转开发d, this part onclick'?

As an example, I have this code that loads on Docready (which uses .change(); so that it runs immediately):

$(function() {
  $('.trigger :checkbox').change(function() {
    $(this).parent().nextAll('ul.hidden').toggle(this.checked);
  }).change();
});

But I alse want to run this code when someone clicks on one of my .trigger classes:

$('.trigger :checkbox').change(function() {
    var $target = $(this).parent().nextAll('.hidden'); // go up a level and then look for the next list with the hidden class
    $(this).parent().toggleClass('open');   // the class of the label needs to change, so find the parent of the checkbox
    $target.fadeToggle();
    if( $(this).is(':checked') ) {
        $target.find('.hidden').css('display', 'none'); // hide all submenus
    } else {
        $target.find(':checkbox').removeAttr('checked'); // untick all checkboxes in sub-menu if unchecking
    }                                                                                   
});

Currently, the click event gets very confused.


You should split out the 'functionality' into functions and then call the different functions from the page load and the change event:

$(function() {

doSomething();

$("#selectElement").change(doSomething());

});

function doSomething() {}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜