我尝试根据用户的选择制作一个隐藏/显示表单的jQuery函数!
以下是我将更好理解的代码。
…
<p id="joinChoice" class="parent">
<a href="" id="mastercardChoice"><span class="overlay"></span></a>
<a href="" id="visaChoice"><span class="overlay"></span></a>
<a href="" id="discoverChoice"><span class="overlay"></span></a>
</p>
…
<div class="joinForm">
<div id="noneForm"></div>
<div id="mastercardForm"></div>
<div id="visaForm"></div>
<div id="discoverForm"></div>
</div>
span#overlay in是一个简单的复选框图像替换!
我只需要一个隐藏/查看所选卡类型的每个表单的功能!
对于#joinChoice,我已经做到了:
$('#joinChoice a').click(function(){
$(this).addClass('on')
.siblings().removeClass('on');
});
你能帮我更多吗
答案 0 :(得分:1)
这样的东西?
HTML
<p id="joinChoice" class="parent">
<a href="javascript:void(0)" id="mastercard"><span class="overlay">Mastercard</span></a>
<a href="javascript:void(0)" id="visa"><span class="overlay">Visa</span></a>
<a href="javascript:void(0)" id="discover"><span class="overlay">Discover</span></a>
</p>
<div class="joinForm">
<div id="noneForm">noneForm</div>
<div id="mastercardForm">mastercardForm</div>
<div id="visaForm">visaForm</div>
<div id="discoverForm">discoverForm</div>
</div>
CSS
.joinForm div {
display: none;
}
.on {
color: red;
background: yellow;
}
的jQuery
$('#joinChoice a').click(function(){
$('#joinChoice a').removeClass('on'); /* remove class from all siblings */
$(this).addClass('on'); /* add class to active sibling */
$('.joinForm div').hide(); /* hide all other forms */
var subElement = '#' + $(this).attr("id") + 'Form';
$( subElement ).show(); /* show active form */
});
和demo
答案 1 :(得分:0)
<强>更新强>
我错过了一条重要的路线:
e.preventDefault();
这会阻止在点击<a>
时重新加载页面。
HTML:
<p id="joinChoice" class="parent">
<a href="" id="mastercardChoice" data-form-id="mastercardForm"><span class="overlay"></span></a>
<a href="" id="visaChoice" data-form-id="visaForm"><span class="overlay"></span></a>
<a href="" id="discoverChoice" data-form-id="discoverForm"><span class="overlay"></span></a>
</p>
Javascript:
$('#joinChoice a').click(function (e) {
// prevents the click event to propagate up the DOM tree
// And thus, prevents the page to reload, in that case..
e.preventDefault();
var $this = $(e.target);
// Reset others
var $links = $this.siblings();
$links.removeClass('on');
$links.each(function(linkEl) {
$( '#'+$(linkEl).data('form-id') ).hide();
});
// Activate user choice..
$this.addClass('on')
$('#'+$this.data('form-id')).show();
});