我有充当开关开/关按钮的链接文字,我想使用它没有任何页面重载。 关闭时,链接具有与开启状态不同的特定类别,网址和文本值。 (即开启它出现绿色/关闭它显示为红色)jQuery的错误 - 开启/关闭链接
略低于你有我使用的那一刻jQuery代码。
$('.off').click(function() {
var element = $(this);
var link = $(this).attr('href');
var newlink = link.replace('off','on');
$.get(link, function(data) {
$('#front').html(data);
$('#front').center().show();
$('#background').show();
if(data == "Button switched.") { element.attr('href', newlink); element.text('on'); element.attr('class', 'on'); }
});
return false;
});
$('.on').click(function() {
var element = $(this);
var link = $(this).attr('href');
var newlink = link.replace('on','off');
$.get(link, function(data) {
$('#front').html(data);
$('#front').center().show();
$('#background').show();
if(data == "Button switched off.") { element.attr('href', newlink); element.text('off'); element.attr('class', 'off'); }
});
return false;
});
和我谈论这个样子的HTML元素:
<a href="engine.php?id=15&switch=on" class="on">on</a>
所以,如果被点击,看起来酷似上面的元素,按钮切换到关闭,所有链接属性被更改,但是当我点击第二次(与新属性的链接),它使AJAX请求,它给我#front
的结果,但它不会再更改链接的属性,因为它应该。
什么问题?
你可能想尝试'removeClass()'http://api.jquery.com/removeClass/和'addClass()'http://api.jquery.com/addClass/而不是改变' attr'。 – ckpepper02
只是一个观察,你几乎可以将这两个函数转换成一个函数,然后根据点击的内容调用交换。它会更干净... –