Possible Duplicate:
How can I check whether a variable is defined in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?

我的 playbook 分为两部分.

The first part sets up a var:

var pagetype = "textpage";

The 2nd part is a simple if statement:

if(pagetype == "textpage") {
//do something
};

Now the 2nd part, the if statement, appears on all pages of my site. But the first part, where the var is declared, only appears on some of my pages.

在没有var的页面上,我自然会遇到以下错误:

Uncaught ReferenceError: pagetype is not defined

所以我的问题是:有没有一种使用JavaScript或JQ的方法来检测变量是否存在(不仅仅是检测是否有数据分配给它)?

I am imagining I would just use another if statment, eg:

if ("a var called pagetypes exists")....

推荐答案

I suspect there are many answers like this on SO but here you go:

if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
  ...
}

Jquery相关问答推荐

当我使用 OwlCarousel 时,没有任何显示

在 JQuery DataTable 中通过按钮单击传递 ID

将 HTML5 Canvas 转换为要上传的文件?

对自定义属性执行客户端验证

jQuery 绑定点击 *ANYTHING* 但 *ELEMENT*

使用 jQuery 和 HTML 导出为 CSV

仅在 _some 字段上通过 Enter 键禁用表单提交

Facebook 风格的 JQuery 自动完成插件

如何在jQuery中 Select 具有特定ID的所有元素?

如何阻止 Chrome 进入调试模式?

使用 jQuery 拖放防止单击事件

输入元素上的 Javascript 更改事件仅在失go 焦点时触发

使用 jQuery DataTables 时禁用第一列的自动排序

jQuery:如果页面底部有外部 JS,为什么要使用 document.ready?

检测 jQuery UI 对话框是否打开

jQuery或javascript查找页面的内存使用情况

jQuery - 从元素内部 Select 元素

JS - 从base64代码中获取图片的宽高

如何使用 ID 变量在 jQuery 中 Select 元素?

jQuery 将换行符转换为 br (nl2br 等效)