jQuery replace text of element on hover

前端 未结 5 754
刺人心
刺人心 2020-12-03 06:04

With jQuery, I\'m trying to replace the text, including the span, inside these links on hover. Then when the user hover\'s off, the original text is displayed again.

相关标签:
5条回答
  • 2020-12-03 06:23

    You'd need to store it in a variable in order to set it back to what it was, try:

    var text;
    
    $(".btn").hover(function () {
        text = $(this).text();
        $(this).text("I'm replaced!");
    },
    function () {
        $(this).text(text);
    });
    
    0 讨论(0)
  • 2020-12-03 06:29

    This should do the trick

    $(function(){
      var prev;    
    
      $('.btn').hover(function(){
      prev = $(this).text();
          $(this).text("I'm replaced!");
      }, function(){
          $(this).text(prev)
      });
    })
    
    0 讨论(0)
  • 2020-12-03 06:33
    $('.btn').hover(
        function() {
            var $this = $(this); // caching $(this)
            $this.data('defaultText', $this.text());
            $this.text("I'm replaced!");
        },
        function() {
            var $this = $(this); // caching $(this)
            $this.text($this.data('defaultText'));
        }
    );
    

    you could save the original text in a data-defaultText attribute stored in the node itself so to avoid variables

    0 讨论(0)
  • 2020-12-03 06:43
    $('.btn').hover(function() {
        // store $(this).text() in a variable     
        $(this).text("I'm replaced!");
    },
    function() {
        // assign it back here
    });
    
    0 讨论(0)
  • 2020-12-03 06:46

    add another function to the hover event like this:

    $('.btn').hover(function(){
        $(this).text("I'm replaced!");
    }, function() {
        $(this).text("Replace me please");
    });
    

    Link for demo

    0 讨论(0)
提交回复
热议问题