jQuery problem with selector

拜拜、爱过 提交于 2019-12-24 11:21:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!