2013-02-26 162 views
0

我有一個問題,如果在回調函數,我不明白爲什麼。回調函數問題jquery

點擊一個div後,文本會根據需要改變,但在第一次拍攝後,它不再起作用。

我的代碼是:

<div id="2">message</div> 
<div id="1">dfdfgdfgrr</div> 

<script src="jquery.js"></script> 
<script> 
$(function() { 

$('#2').toggle(); 

function test() { 
    $(document).on('click', '#1', function() { 
     $('#2').toggle(300, function() { 
      if($('#1').text('show')){ 
       $('#1').text('hide'); 
      }else{ 
       $('#1').text('show'); 
      } 
     }); 
    }); 
} 

test(); 


}); 
</script> 

http://jsfiddle.net/manguo_manguo/cydjY/

回答

1
$('#1').text(function(i, t) { return t == 'show' ? 'hide' : 'show' }); 
1
 if($('#1').text() === 'show'){ 
      $('#1').text('hide'); 
     }else{ 
      $('#1').text('show'); 
     } 
1

您正在使用$('#1').text("show")代替$('#1').text() == "show"

$('#2').toggle(); 

function test() { 
    $(document).on('click', '#1', function() { 
     $('#2').toggle(300, function() { 
      if($('#1').text() == 'show'){ 
       $('#1').text('hide'); 
      }else{ 
       $('#1').text('show'); 
      } 
     }); 
    }); 
} 

test(); 
1

另一種解決方案是正確的,但第一次是不顯示顯示標籤。

這是一個完整的解決方案:

$(function() { 

$('#2').toggle(); 

function test() { 
    $(document).on('click', '#1', function() { 
     $('#2').toggle(300, function() { 
      if($('#1').text() == 'hide'){ 
       $('#1').text('show'); 
      }else{ 
       $('#1').text('hide'); 
      } 
     }); 
    }); 
} 

test(); 
$('#1').text('show'); 
}); 

嘗試的示例here