jQuery change events on docready

2019-09-03 16:13发布

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 load, 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.

1条回答
神经病院院长
2楼-- · 2019-09-03 16:45

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() {}
查看更多
登录 后发表回答