这段代码工作得很好,除了一件事,我不明白为什么它会出错。对于顶部的图片,或者"#个人保险",我必须点击两次才能实现该功能。这只是您第一次使用该功能。如果单击任何其他ID,"#businessinsurance"或"#assetservation",则该功能在第一次单击时即可工作。这个函数只是在单击其中一个"insortypes"图像时,在div"#insorpic"中显示一个div。所以我的问题是,我该怎么做才能让它在第一次点击时发挥作用?
此外,我是否可以更改一些内容,使div显示更多。。。优美它只是看起来,如果它滑进去或类似的酷东西就太好了!但事实上,我只需要在第一个问题上得到帮助,如果你帮我解决这一部分,那么你就酷多了!
链接到使用代码的网站网站
下面是HTML和jQuery。
HTML
<div id="insurtypes"> <a href='#personalinsurnace'>
<img src="img/personal_insurance.png" />
</a> <a href='#businessinsurance'>
<img src="img/business_insurance.png" />
</a>
<a href='#assetpereservation'>
<img src="img/asset_preservation.png" />
</a>
</div>
<div id="insurpic">
<div id="personalinsurnace"><b>Personal Insurance Services</b>
<br />choose the service you are interested in!
<ul>
<li></li>
</ul>
</div>
<div id="businessinsurance"><b>Business Insurance Services</b>
<br />choose the service you are interested in!
<ul>
<li></li>
</ul>
</div>
<div id="assetpereservation"><b>Asset Preservation Services</b>
<br />choose the service you are interested in!
<ul>
<li></li>
</ul>
</div>
</div>
jQuery
$('#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) {
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();
}
});
});
您必须在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();