我正在尝试同时向单击的链接添加一个类,同时从DOM中删除相同的类。添加类的代码部分可以工作,但它只是让类一次又一次出现。我也对javascript解决方案与服务器端解决方案的功效感到好奇。
$(document).ready(function() {
$(function() {
$('#header a span').click(function(e) {
var title = this.innerText;
//possible browser compatability from .text?
$('selected').removeClass('selected');
$(this).addClass('selected');
// Also prevent the link from being followed:
});
});
<div id="header" class="ui-corner-all ui-buttonset">
<a title="index" href="#" class="link" ><span>home</span></a>
<a title="code" href="#" class="link" ><span>code</span></a>
<a title="design" href="#" class="link" ><span>design</span></a>
<a title="illustration" href="#"class="link" ><span>illustration</span></a>
<a title="writing" href="#" class="link" ><span>writing</span></a>
<a title="links" href="#" class="selected" ><span>links</span></a>
<a title="about" href="#" class="selected"><span>about</span></a>
</div>
答案 0 :(得分:1)
$('selected').removeClass('selected');
应该是
$('.selected').removeClass('selected');
答案 1 :(得分:1)
将您的JS更改为:
$(document).ready(function() {
$('#header a span').click(function(e) {
var title = $(this).text();
//possible browser compatability from .text?
$('.selected').removeClass('selected');
$(this).addClass('selected');
// Also prevent the link from being followed:
return false;
});
});
顺便说一下,您希望selected
元素或span
元素上的课程a
,您的JS表示span
,但您的html表示a
}。
答案 2 :(得分:0)
你的课堂需要(。)在此之前我想。