JQuery函数不会在首次点击时触发,但在所有后续点击中的行为均与预期的一样 [英] JQuery function doesn't fire on first click, but behaves as expected on all subsequent clicks

查看:75
本文介绍了JQuery函数不会在首次点击时触发,但在所有后续点击中的行为均与预期的一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要选中的链接即可显示为选中状态并显示所指示的div,同时隐藏其他两个.这是jsfiddle:

I simply need the selected link to show as selected and to show the indicated div while hiding the other two. Here's the jsfiddle:

http://jsfiddle.net/HZ4CZ/1/

为什么第一次点击不起作用,但是之后每次点击都起作用?

Why is it not working the first click, but working every click after that?

$(document).ready(function() {
    $('ul#chooseType li a').click(function(e) {   
        $('#active').click(function(){
            $('.activeDiv').removeClass('show_hide');
            $('.inactiveDiv').addClass('show_hide');
            $('.thirdMenuDiv').addClass('show_hide');
            $('#active').addClass('selected');
            $('#inactive').removeClass('selected');
            $('#thirdMenu').removeClass('selected');
        });
        $('#inactive').click(function(){
            $('.activeDiv').addClass('show_hide');
            $('.inactiveDiv').removeClass('show_hide');
            $('.thirdMenuDiv').addClass('show_hide');
            $('#active').removeClass('selected');
            $('#inactive').addClass('selected');
            $('#thirdMenu').removeClass('selected');
        });
        $('#thirdMenu').click(function(){
            $('.activeDiv').addClass('show_hide');
            $('.inactiveDiv').addClass('show_hide');
            $('.thirdMenuDiv').removeClass('show_hide');
            $('#active').removeClass('selected');
            $('#inactive').removeClass('selected');
            $('#thirdMenu').addClass('selected');
        });

    });
});

推荐答案

不要嵌套您的点击处理程序!摆脱所有包含的处理程序,一切就绪.小提琴: http://jsfiddle.net/tymeJV/HZ4CZ/2/

Dont nest your click handlers! Get rid of that all encompassing handler and you're set. Fiddle: http://jsfiddle.net/tymeJV/HZ4CZ/2/

此处理程序的轴:$('ul#chooseType li a').click(function(e) {

之所以有效,是因为您的点击处理程序实际上没有在页面加载时受到约束,而是在首次点击后便受到约束.

It works because none of your click handlers actually get bound on page load, they get bound after the initial click.

这篇关于JQuery函数不会在首次点击时触发,但在所有后续点击中的行为均与预期的一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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