Javascript Jquery Uncaught TypeError:无法读取未定义的属性“替换”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32231409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Uncaught TypeError: Cannot read property 'replace' of undefined
提问by innovation
Anyone can tell me why i am getting this error:
任何人都可以告诉我为什么我会收到此错误:
Uncaught TypeError: Cannot read property 'replace' of undefined
未捕获的类型错误:无法读取未定义的属性“替换”
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();
采纳答案by War10ck
I believe that this error is caused by one of two scenarios, based on the given information above:
根据上述给定的信息,我认为此错误是由两种情况之一引起的:
$('#NewPostBody)
is not being found in the DOM$('#NewPostBody)
is being found but has no class attribute.
$('#NewPostBody)
在 DOM 中找不到$('#NewPostBody)
正在被找到但没有类属性。
This can be solved using the following method:
这可以使用以下方法解决:
var pid = ($('#NewPostBody').length && $('#NewPostBody').attr('class'))
? $('#NewPostBody').attr('class')
: "";
The ternary operator along with truthy/falsylogic should result in either the class being returned or an empty string. Either way, pid.replace('post-t', '')
can safely be called without resulting in an error.
三元运算符以及真/假逻辑应该导致返回类或空字符串。无论哪种方式,pid.replace('post-t', '')
都可以安全地调用而不会导致错误。