jQuery在docready上更改事件 [英] jQuery change events on docready

查看:93
本文介绍了jQuery在docready上更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在页面最初加载时运行功能的一部分,但是大多数change事件仅应在随后与目标进行交互时运行.

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.

问题在于这两个事件不是不相关的-在页面加载时,我想显示某些div,然后我想要一个单击动作来显示/隐藏div.我可以将这两个部分分开运行,但无法将它们组合在一起.

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.

我的问题是,实现这种分离的最佳方法是什么? jQuery中是否有一种方法说只运行一次此部分"或在页面加载时运行此部分,此部分在onclick上运行"?

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'?

作为一个例子,我将这段代码加载到Docready上(使用.change();以便立即运行):

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();
});

但是我还想在有人单击我的.trigger类之一时运行此代码:

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() {}

这篇关于jQuery在docready上更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆