发布后div中没有​​显示任何内容

时间:2012-02-23 17:55:38

标签: javascript jquery html css ajax

$(document).ready(function() {
    $("#register button[name=btnPosta]").click(function() {
        console.log('clicked');

        thisBtn = $(this);
        parent = $(this).parent();
        name = parent.data('name');

        $(this).attr('disabled', true);
        $.post('register.php', {
            name: ('name')
        }, function(data) {
            console.log('Ajax success');
            parent.next('#message').html(data);
            thisBtn.attr('disabled', false); // reset  });

            console.log('Ajax success');
        });
    });
});​

此功能用于显示#message div中的名称 但是div中没有显示任何内容。

2 个答案:

答案 0 :(得分:1)

假设您的标记类似于您在一小时前在your duplicate post中发布的标记:

...
<tr> 
    <td>  <td> 
    <td> <button  class='regular' id = "btnPost" name='save'> Log In  </button></td> 
</tr> 
...

问题在于您使用.next()。将选择器参数传递给.next()时,只有在下一个兄弟元素与选择器匹配时才会得到结果。您对parent.next("#message")的调用会返回一个空的jQuery对象,因为:

  1. 按钮的父元素的下一个兄弟(<td>)的ID不是message
  2. 实际上,<td>没有下一个兄弟。
  3. 由于parent.next("#message")返回一个空的jQuery对象,因此在其上调用.html()无效。解决方案就是直接使用$("#message")

    $('#message').html(data);
    



    我的original answer只是一只红鲱鱼:

    确保在定义变量时务必使用var关键字。如果没有var,则在Global对象(或在浏览器中运行JavaScript时window)上创建属性。但是,parent已经是window的属性。在IE中,window.parent是只读的,因此您的值永远不会设置,当您调用parent.data()时会出现错误。

    当我使用var时,您的代码适用于我:http://jsfiddle.net/gilly3/MkS9X/

答案 1 :(得分:0)

$(function() {
    $("#register").find("button[name=btnPosta]").click(function() {
        console.log('clicked');

        //notice the use of `var` to keep the variables local, which will be faster
        var thisBtn = $(this),
            parent  = thisBtn.parent(),
            name    = parent.data('name');

        //notice the use of `.prop()` instead of `.attr()`, `.prop()` is new as of jQuery 1.6, so if you are using an older version then `.attr()` is the way to go
        thisBtn.prop('disabled', true);
        $.post('register.php', {
            name: name //notice here that this references the `name` variable set further up
        }, function(data) {
            console.log('Ajax success');

            parent.next('#message').html(data);
            thisBtn.prop('disabled', false); // reset  });

            console.log('Ajax success');
        });
    });
});​

为您的代码提供一些建议。主要是变量是在全球范围内创建的,最有可能是没有理由的。

相关问题