Jquery 必须单击图像两次才能使功能正常工作

Jquery 必须单击图像两次才能使功能正常工作,jquery,html,function,Jquery,Html,Function,这段代码工作得很好,除了一件事,我不明白为什么它会出错。对于顶部图像,或personalinsurance,我必须单击它两次才能实现该功能。这只是您第一次使用该功能。如果单击了businessinsurance或assetpreservation中的任何其他ID,则该函数将在第一次单击时起作用。当单击某个InsureTypes图像时,此函数仅使div显示在div insurepic中。所以我的问题是,我能做些什么让它在第一次点击时工作 还有,有没有什么我可以改变的,让div表现得更优雅一点?它只

这段代码工作得很好,除了一件事,我不明白为什么它会出错。对于顶部图像,或personalinsurance,我必须单击它两次才能实现该功能。这只是您第一次使用该功能。如果单击了businessinsurance或assetpreservation中的任何其他ID,则该函数将在第一次单击时起作用。当单击某个InsureTypes图像时,此函数仅使div显示在div insurepic中。所以我的问题是,我能做些什么让它在第一次点击时工作

还有,有没有什么我可以改变的,让div表现得更优雅一点?它只是出现了,如果它滑进去或者像那样酷的东西,那就太棒了!但实际上,我只需要在第一个问题上得到帮助,如果你帮我解决这个问题,那么你就酷多了

链接到使用代码的网站

下面是HTML和jQuery

HTML

您必须在click事件开始后立即添加e.preventDefault

单击事件后立即添加:

$(this).on('click', 'a', function (e) {
完整代码:

$('#insurtypes').each(function () {

    var $active, $content, $links = $(this).find('a');

    $active = $($links.filter('[href="' + location.hash + '"]')[0] || $links[0]);
    $active.addClass('active');
    $content = $($active.attr('href'));

    $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

    $(this).on('click', 'a', function (e) {
        e.preventDefault();
        if ($(this).is('.active')) {
            $('.active').removeClass('active');
            $content.hide();
        } else {
            $('.active').removeClass('active');
            $content.hide();
            $active = $(this);
            $content = $($(this).attr('href'));

            $active.addClass('active');
            $content.show();
        }
    });
});

并确保删除e.preventDefault;在事件函数的最后一行中

运行没有问题就像加载一样,所有内容都设置为活动,然后单击它将其隐藏。什么不起作用?我需要提供更多信息吗?我知道它在网站上不能正常工作。那么问题可能出在css上了吗?所有3种类型都使用相同的css减号颜色。我只需单击2次,该函数就可以在顶部图像上工作。添加链接到文章中使用此代码的网站。不幸的是,我仍然必须单击顶部图像两次,该函数才能工作,即使您建议对代码进行更改。
$(this).on('click', 'a', function (e) {
$('#insurtypes').each(function () {

    var $active, $content, $links = $(this).find('a');

    $active = $($links.filter('[href="' + location.hash + '"]')[0] || $links[0]);
    $active.addClass('active');
    $content = $($active.attr('href'));

    $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

    $(this).on('click', 'a', function (e) {
        e.preventDefault();
        if ($(this).is('.active')) {
            $('.active').removeClass('active');
            $content.hide();
        } else {
            $('.active').removeClass('active');
            $content.hide();
            $active = $(this);
            $content = $($(this).attr('href'));

            $active.addClass('active');
            $content.show();
        }
    });
});