jQuery and switch between two cases
I have this code
<a href="#">
<span style="border-right: medium none;" class="Yes">Yes</span>
</a>
<a href="#">开发者_运维问答;
<span class="No">No</span>
</a>
if no is current
I want when click on yes class calling current
adding on yes span and delete current
class from no.
If yes current
I want when click on no class calling current
adding on no span and delete current
class from yes.
I want each case happen in just one click.
Try this:
$(".Yes, .No").click(function() {
if(!$(this).hasClass("current"))
$(".Yes, .No").toggleClass("current");
});
Yes
and No
both fire the click, but the action only happens if the click didn't happen on the current one. Just set current to whatever you want initially, the toggle will take care of it from then on as you describe in the question.
Here is a sample. This is a first cut, may be this can be optimized. All I am trying to do is remove current
class from all the elements and add it to current one.
You have to modify your html to have a unique class
<a href="#">
<span style="border-right: medium none;" class="Yes yesno">Yes</span>
</a>
<a href="#">
<span class="No yesno">No</span>
</a>
This is the jQuery code
$('.yesno').click(function(){
$('.yesno').each(function(i, v){
$(v).removeClass('current');
});
$(this).addClass('current');
});
see if it helps..
Perhaps I am misinterpreting your question, but it looks like you're trying to produce something that behaves like Radio Buttons.
<div class="radioButtons">
<a href="#">Yes</a>
<a href="#">No</a>
<a href="#">Maybe</a>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function select(event) {
var clicked = $(event.target);
clicked.siblings('a').removeClass('selected');
clicked.addClass('selected');
}
$(function() {
$('.radioButtons a').click(select);
});
</script>
精彩评论