问题
I have a very strange problem. I am using jQuery to intercept a particular tag click.
I have:
<a class="question">lorem ipsum</a>
<a class="question_selected">lorem ipsum</a>
<a class="question">lorem ipsum</a>
<a class="question">lorem ipsum</a>
And my jQuery is:
$("a.question").click(function(){.....});
It should intercept the <a>
click where class="question" but it is also intercepting whenever I click <a class="question_selected">
.
What can be the problem?
EDIT:
I am actually changing the classes on click. The tag that I click should become "question_selected" and all other should be "question". Here is the jQuery: $('a.question_selected').removeClass('question_selected').addClass('question'); $(this).addClass('question_selected').removeClass('question');
回答1:
Remove the underscore from the class name. Perhaps there's a bug in jQuery regarding that.
Otherwise, this doesn't directly answer your question, but some suggestions:
First of all, instead of swapping the class, I'd just use two classes:
<a class="question">lorem ipsum</a>
<a class="question selected">lorem ipsum</a>
Then, in your jQuery, I'd cache your questions:
$questions = $('a.question');
And then your jquery can be:
$questions.click(function(){
$questions.filter('.selected').removeClass('selected');
$(this).addClass('selected');
})
回答2:
http://jsfiddle.net/gJtDS/1/
This works just fine for me. Something else in your code must be conflicting.
回答3:
Have you forgotten a closing tag?
Have you done anything with positioning that might place padding from another element over the top of the other one?
Are you dynamically updating the classes? Are you assigning the click handler before or after those updates? Are you sure you don't want live()
instead?
回答4:
$("a.question").live('click',function(){
$(this).removeClass('question');
$(this).addClass('question_selected');
$(this).siblings('a').removeClass();
$(this).siblings('a').addClass('question');
});
来源:https://stackoverflow.com/questions/6560872/jquery-problem-with-selector