Is variable set/defined issue?

房东的猫 提交于 2019-12-12 03:14:49

问题


I'm using a forum software where you can pull up an avatar link using this: {$mybb->user['avatar']}

If no avatar is set then nothing is returned. I want to show an image if no avatar is set.

Currently the HTML is setup like this:

    <div id="avatar"><div style="background: url({$mybb->user['avatar']}) center center no-repeat;"></div></div>

The outer div is empty and in the background. This one is the one I'm adding a class too (.defaultavatar) so that a default avatar will display.

The inner div is the one with the avatar displaying. If no avatar is uploaded/selected then it will appear blank.

This is the javascript I'm using:

    var myavatar = {$mybb->user['avatar']};

    if(typeof(myavatar) = null){ 
        jQuery('#avatar').addClass('defaultavatar');
    }

If the avatar URL is empty I want the class defaultavatar to be added to the first div.

How can I do this (get it to work)?

Thanks very much, Jack Clarke


回答1:


There are two meanings for undefined in javascript. I'm not sure what their exact names are, for my example I will call them undefined and REALLY undefined.

The regular undefined is what you get when you try to get a value from something that has been declared but not initialized. In other words, the interpreter knows the thing you're talking about, but that thing has no value yet.

You can use a simple if statement to cast your variable to a boolean to check if it is this type of undefined. Be aware that this cast will also cast empty strings '' and numeric 0 to false as well. If you need to consider empty strings and numeric 0 as well, use myDeclaredVariable === undefined for the condition instead.

if (myDeclaredVariable) {
    // myDeclaredVariable is initialized with a "truthy" value
} else {
    // myDeclaredVariable is either uninitialized or has a "falsey" value
}

The REALLY undefined is what you get when you try to access a random variable without ever even declaring it. The interpreter has no idea what you are talking about and it will throw a javascript exception if you try to do anything with it. To handle this situation, you need to use the typeof operator.

if (typeof myPossiblyDeclaredVariable !== 'undefined') {
    // myPossiblyDeclaredVariable has been declared
} else {
    // myPossiblyDeclaredVariable has not been declared yet
}

You can see a related StackOverflow question here.




回答2:


in your if condition, the syntax has a problem. Single equal is assignment.

at least change this

if(typeof(myavatar) = null)   

to

if (typeof myavatar == 'undefined')



回答3:


Depending on what {$mybb->user['avatar'] returns, it may be sufficient to do:

if (myavatar) {
  // do stuff
}  


来源:https://stackoverflow.com/questions/10098816/is-variable-set-defined-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!