【问题标题】:Jquery Uncaught TypeError: Cannot read property 'replace' of undefinedJquery Uncaught TypeError:无法读取未定义的属性“替换”
【发布时间】:2015-08-26 16:00:49
【问题描述】:

谁能告诉我为什么会出现这个错误:

未捕获的类型错误:无法读取未定义的“替换”属性

function checkNewPost(x) {
        var pid = $('#NewPostbody').attr('class');
        if(pid === 'post-t') {
            setTimeout(checkNewPost, <?php echo $p_id; ?>);
        } else {
            $.ajax({
                type: "POST",
                url: "/html_postReply.php",
                data: "pid="+pid.replace('post-t', '')+"&type=1", 
                success: function(html) {
                    if(html) {
                        $('.tekin').append(html);
                        jQuery("span.timeago").timeago();
                        $(".tekin").scrollTop($(".tekin")[0].scrollHeight);
                    }
                    if(!x) {
                        setTimeout(checkNewPost, <?php echo $p_id; ?>);
                    }
               }
            });
        }
    }
    checkNewPost();

【问题讨论】:

  • 这只是表示pidundefined
  • 如果您可以使用回退(例如空字符串),您可以使用|| 运算符:var pid = $('#NewPostbody').attr('class') || '';
  • 如果我编辑了你的标题和标签,你会反对吗?老实说,这与 jQuery 没有任何关系。这是由 undefined 值引起的标准 JavaScript 错误消息...

标签: javascript jquery ajax


【解决方案1】:

根据上面给定的信息,我认为此错误是由以下两种情况之一引起的:

  1. 在 DOM 中找不到$('#NewPostBody)

  2. $('#NewPostBody) 被找到,但没有类属性。

这可以通过以下方法解决:

var pid = ($('#NewPostBody').length && $('#NewPostBody').attr('class')) 
    ? $('#NewPostBody').attr('class') 
    : "";

三元运算符和 truthy/falsy 逻辑应该导致返回类或空字符串。无论哪种方式,都可以安全地调用 pid.replace('post-t', '') 而不会导致错误。

【讨论】:

  • War10ck 你的答案解决了我的问题..我不清楚请提供有关此答案的信息。
猜你喜欢
  • 2015-04-04
  • 1970-01-01
  • 2018-01-19
  • 2015-05-07
  • 1970-01-01
  • 2015-05-29
  • 2019-09-07
相关资源
最近更新 更多