简体   繁体   English

检查未定义的变量在Chrome中不起作用

[英]Checking for undefined variable not working in chrome

I am checking if a variable is defined or not. 我正在检查是否定义了变量。 It is working right in Firefox and when it comes to Chrome it is not working: 它在Firefox中可以正常使用,而在Chrome上则无法使用:

if(window[myClass] == undefined)
{
    return;
}

If the variable is not defined it should return. 如果未定义变量,则应返回。

I am using window[myClass] because I am taking name of the id from onclick event and using same named variable as id if variable is defined then else part should or if not defined then if part should work. 我之所以使用window[myClass]是因为我从onclick事件中获取ID的名称,并且使用相同的命名变量作为ID(如果定义了变量,则应该定义其他部分,或者如果未定义则确定部分应该工作)。

You should be doing something like this to check whether window[myclass] is defined or not: 您应该这样做,以检查是否定义了window[myclass]

if (typeof window[myclass] === 'undefined') {

But if I understand the question correctly, you might be looking to see if window[myclass] exists. 但是,如果我正确理解了这个问题,那么您可能正在寻找window[myclass]存在。 Usually you do that like so: 通常,您这样做是这样的:

if (window.hasOwnProperty(myclass)) {

Also, is myclass a variable or a string ( 'myclass' )? 另外, myclass是变量还是字符串( 'myclass' )?

From the last sentence in your question, sounds like myClass is actually ID of some element in your document. 从问题的最后一句话开始,听起来myClass实际上是文档中某些元素的ID。

In such case you should use such code to check if such element really exists: 在这种情况下,您应该使用以下代码检查该元素是否确实存在:

if (!document.getElementById(myClass))
    return;

This will cancel the function when element with such ID does not exist. 当具有该ID的元素不存在时,这将取消该功能。

if (typeof window[myClass] !== 'undefined') {
    //do stuff
} else {
    alert('undefined');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM