未捕获的TypeError:无法读取未定义的属性'toLowerCase'
at Object.<anonymous> (<anonymous>:16:76) at Function.each (jquery.js?v=1.4.4:34) at Object.success (<anonymous>:10:13) at Function.handleSuccess (jquery.js?v=1.4.4:143) at XMLHttpRequest.w.onreadystatechange (jquery.js?v=1.4.4:142)
我在尝试使用toLowerCase()函数时,在注释掉的if代码中继续出现上述错误,代码如下:
(function($) {
$.ajax({
url: "/node.json",
data: {'type': "resource_page", 'page': 3},
dataType: "json",
type: "GET",
success: function (response) {
$.each(response.list, function(k, resource) {
var title = resource.title;
var description = resource.body.value;
if(title.toLowerCase().indexOf("biology") >= 0) { console.log(description.toLowerCase().indexOf("biology")); };
//if(title.toLowerCase().indexOf("biology") >= 0 || description.toLowerCase().indexOf("biology") >=0) { console.log(title); };
});
}
});
}(jQuery));
当我consol.log()它一切正常(我得到226的结果说“生物”确实出现在字符串中)。我甚至可以说:
if(title.toLowerCase().indexOf("biology") >= 0) { console.log(description.toLowerCase()); };
仍然可以获得<p>this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.</p>
我不确定为什么我会收到错误的描述而不是标题。我已经尝试在描述中使用toLowerCase()之前在if中使用它但是没有用。我只能在console.logging它时使用它。任何人都可以帮助我。非常感谢你!
答案 0 :(得分:1)
你得到错误的原因是你有&#34; title&#34;或描述等于undefined。以下示例引发了同样的异常错误:
var title;
var description = '<p>this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.</p>';
console.log(description.toLowerCase().indexOf("biology"))
if(title.toLowerCase().indexOf("biology") >= 0 || description.toLowerCase().indexOf("biology") >=0) {
console.log(title);
};
&#13;
但是,我建议您在if语句中检查它们是否为空或未定义,如下所示:
var title;
var description = '<p>this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.</p>';
console.log(description.toLowerCase().indexOf("biology"))
if((title && title.toLowerCase().indexOf("biology") >= 0) || (description && description.toLowerCase().indexOf("biology") >=0)) {
console.log(title);
console.log('It works fine');
};
&#13;
你看它运作正常。