2012-05-22 3 views
8

jQuery를 사용하면 스윙을 포함한 텍스트를 호버의 이러한 링크 내부로 대체하려고합니다. 그런 다음 사용자 호버가 꺼지면 원래 텍스트가 다시 표시됩니다.jQuery가 호버에있는 요소의 텍스트를 바꿉니다.

<a class="btn" href="#"> 
    <img src="#" alt=""/> 
    <span>Replace me</span> please 
</a> 

<a class="btn" href="#"> 
    <img src="#" alt=""/> 
    <span>Replace me</span> please 
</a> 

최종 출력은 내가 주위에 놀겠 그러나 그것을 다시 교체하는 방법을 잘 모르겠어요

<a class="btn" href="#"> 
    <img src="#" alt=""/> 
    I'm replaced! 
</a> 

을해야합니다. 어떤 아이디어?

$('.btn').hover(function(){ 
    $(this).text("I'm replaced!"); 
}); 
+0

을 위해 * 모든 * 내용이 몇 가지 요소 안에 있었다 교체 할 경우 훨씬 쉬울 것이다. – Jon

+0

jQuery로 끝내야합니까, 아니면 정적 텍스트입니까? – Paul

+0

http://api.jquery.com/mouseover/#example-0는 –

답변

21
$('.btn').hover(
    function() { 
     var $this = $(this); // caching $(this) 
     $this.data('initialText', $this.text()); 
     $this.text("I'm replaced!"); 
    }, 
    function() { 
     var $this = $(this); // caching $(this) 
     $this.text($this.data('initialText')); 
    } 
); 

는 자체가 너무 변수

+1

을 43 초 전에 게시했으나 재미있는 점은 내 인터넷이 전송을 클릭하면 두 번째로 다운 된 것으로 나타났습니다. 내가 보낸 때 captcha를 입력하려면 –

+0

+1 data-initialText –

+0

개인적으로 이것은 이것을 대체하지만, 마우스가 사라지면 여전히 새로운 텍스트를 유지합니다! – Dikeneko

4

이 트릭을해야을 방지하기 위해 노드에 저장된 data-initialText 속성에 원본 텍스트를 절약 할 수

$(function(){ 
    var prev;  

    $('.btn').hover(function(){ 
    prev = $(this).text(); 
     $(this).text("I'm replaced!"); 
    }, function(){ 
     $(this).text(prev) 
    }); 
}) 
1
$('.btn').hover(function() { 
    // store $(this).text() in a variable  
    $(this).text("I'm replaced!"); 
}, 
function() { 
    // assign it back here 
}); 
0

당신에게 ' d 변수를 다시 원래대로 설정하려면 변수에 저장해야합니다.

var text; 

$(".btn").hover(function() { 
    text = $(this).text(); 
    $(this).text("I'm replaced!"); 
}, 
function() { 
    $(this).text(text); 
}); 
1

이 같은 호버 이벤트에 다른 기능을 추가

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

Link 데모

+0

와우 이제 얼마나 느린지 깨닫고 ... jsfiddle 링크는 나쁜 아이디어였습니다. '( – optimusprime619

관련 문제