jquery为什么这不起作用?

时间:2011-04-24 06:01:23

标签: jquery

$(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,然后在模糊上将其更改为发布注释。

4 个答案:

答案 0 :(得分:2)

正如zerkms所说,this.'Post a comment'没有意义。

它会给你......

  

未捕获的SyntaxError:意外的字符串

你可能只是指字符串'Post a comment'

此外,this是本机DOM元素,您需要用$()包装它以使其成为jQuery对象。

答案 1 :(得分:1)

以下代码应该有效:

     $(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 :(得分:1)

通过向placeholder="Post a comment"添加<textarea>,您可以更好地使用它。虽然一些旧的浏览器不支持它,但它在现代浏览器中运行良好,不需要任何脚本。

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

答案 3 :(得分: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');
    }
    }
    );
    });