简体   繁体   中英

Nested If Statement Inside Javascript Variable

I have a javascript variable that is a consolidation of many different lines of text (html markup). See below. the info from the image property of the data object I'm injecting into this function may or may not be blank. So, I want a basic if statement to check if it is blank and output some other text if it is.

function(data) {

    var div = [
        <a href="/profile/'+data.message.name+'">',
            if (data.message.image == "") {
                // Some other string
            }
            <img src="/images/profiles/'+data.message.image+'" alt="#"/>',
        </a>',  
    ].join('');
}

Is it possible to nest an If statement in a variable like this? If so, what's the proper syntax?

Thanks!

Conditional (Ternary) Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename = (condition) ? value1:value2 

"" will be falsey value hence you could try the same using || operators.

Try this:

 function test(data) { var image = 'Some other string'; var div = [ '<a href="/profile/' + data.message.name + '">', '<img src="/images/profiles/' + (data.message.image || image) + '" alt="#"/>', '</a>' ].join(''); alert(div); } test({ message: { name: 'Test Name', image: '' } }); 

I don't know for what you want to write this kind of code you can use Jquery append method for your solution.

For your code this will work

div = []
div.push '<a href="/profile/'+data.message.name+'">'
if data.message.image == ""
    //do something
    div.push "someting"
div.push '<img src="/images/profiles/'+data.message.image+'" alt="#"/>'
div.push '</a>'
div.join('')

This code is written in coffee but you will understand it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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