2011-11-21 113 views
0

我的問題是,我有一個按鈕,當用戶將鼠標懸停在它上面,它應該改變文本..當他們徘徊它應該回到以前是如何。jQuery懸停不停止

這裏是我的jQuery

$(document).ready(function() { 
    $("#followingbutton").hover (
     function() { 
      $(this).replaceWith("<input type='submit' value='Unfollow' id='followingbutton' class='button red' />"); 
     }, 
     function() { 
      $(this).replaceWith("<input type='submit' value='Following' id='followingbutton' class='button green' />"); 
    }); 
}); 

它應該像twitter的後續/取消關注按鈕。任何人都可以爲我揭開一些光明嗎?

編輯:一切工作正常,但它不會「unhover」

+0

爲什麼不只是c增加價值和班級? – Rodolphe

回答

2

爲什麼不類似的東西(未經測試):

$(document).ready(function() { 
    $("#followingbutton").hover (
     function() { 
      $(this).val('Unfollow') 
        .attr('class', 'button red'); 
     }, 
     function() { 
      $(this).val('Following') 
        .attr('class', 'button green'); 
    }); 
}); 
+0

謝謝!這解決了我的問題:) – 2kan

0

你爲什麼不嘗試做這樣的事情?

$(document).ready(function() { 
    $("#followingbutton").hover (
     function() { 
      $(this).removeClass('green').addClass('red').attr('value', 'Unfollow'); 
     }, 
     function() { 
      $(this).removeClass('red').addClass('green').attr('value', 'Follow'); 
    }); 
}); 
1

它不會因爲事件沒有被綁定,因爲您已經替換了元素。

只要改變值和類來代替:

$("#followingbutton").hover (
    function() { 
     $(this).val('Unfollow').toggleClass('red green'); 
    }, 
    function() { 
     $(this).val('Following').toggleClass('red green'); 
}); 

示例 - http://jsfiddle.net/infernalbadger/ETVpK/1/

0

這是因爲你刪除具有事件偵聽器,比具有類似元素

替換元素試試這個:

$(document).ready(function() { 
    $("#followingbutton").hover (
     function() { 
      this.value = 'Unfollow'; 
      this.className = 'button red'; 
     }, 
     function() { 
      this.value = 'Following'; 
      this.className = 'button green'; 
    }); 
});