我有充當開關開/關按鈕的鏈接文字,我想使用它沒有任何頁面重載。 關閉時,鏈接具有與開啓狀態不同的特定類別,網址和文本值。 (即開啓它出現綠色/關閉它顯示爲紅色)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
只是一個觀察,你幾乎可以將這兩個函數轉換成一個函數,然後根據點擊的內容調用交換。它會更乾淨... –