2011-04-24 85 views
0
$(document).ready(function() 
{ 
    $('#comment textarea').click(function() 
    { 
     if (this.value == this.'Post a comment') 
     { 
      this.value = ''; 
     } 
    }); 

    $('#comment textarea').blur(function() 
    { 
     if (this.value == '') 
     { 
      this.value = this.'Post a comment'; 
     } 
    }); 
}); 

我有這個腳本卡在一個PHP文件。但它不起作用。 textarea的默認值是發表評論。該腳本應該將textarea的值在點擊時更改爲null,然後在blur上將其更改回發佈評論。jquery爲什麼這不工作?

+5

'THIS.VALUE == this.'Post一個comment'' ---這是什麼!? – zerkms 2011-04-24 06:03:13

回答

1

的followig代碼應工作:

 $(document).ready(function() { 
     $('#comment textarea').click(
      function() { 
       if (this.value == 'Post a comment') { 
        this.value = ''; 
       } 
      } 
     ); 
     $('#comment textarea').blur(
      function() { 
       if (this.value == '') { 
        this.value = 'Post a comment'; 
       } 
      } 
     ); 
    }); 
2

由於zerkms表示,this.'Post a comment'沒有意義。

它會給你...

Uncaught SyntaxError: Unexpected string

你可能只是意味着該字符串'Post a comment'

另外,this是原生DOM元素,您需要用$()來包裝它,使其成爲jQuery對象。

0

這個代碼,我認爲應該工作(如果你使用jQuery):

$(document).ready(function() { 
    $('#comment textarea').click(
    function() { 
    if ($(this).val() == 'Post a comment') { 
    $(this).val(''); 
    } 
    } 
    ); 
    $('#comment textarea').blur(
    function() { 
    if ($(this).val() == '') { 
    $(this).val('Post a comment'); 
    } 
    } 
    ); 
    }); 
1

你可以做過多的使用更好的加入到placeholder="Post a comment"你的<textarea>。儘管某些舊瀏覽器不支持這種功能,但它在現代瀏覽器中運行良好,並且不需要任何腳本。

演示:http://jsfiddle.net/ThiefMaster/vVxrp/

+0

+1提供'placeholder'屬性。 – alex 2011-04-24 08:26:47