简体   繁体   中英

How to create if statement inside embedded HTML in JavaScript to show CSS class

How to display one of two classes based on if there is data in the js array.

eg if there is responseData.title show class grey else class white

I am trying this now:

let resultHTML = '<article class="item">\
                    <div class="post-main">\
                        <header class="clear">\
                            <a href="' + responseData.url + '"</a>\
                            <span class="post-date">just now</span>\
                        </header>\
                        'if (responseData.title) {
                            '<section class="grey">'
                        } else {
                            '<section class="white">'
                        }'\
                            ' + articleImage + '\
                            <h3>' + responseData.title + '</h3>\
                            <div class="post-about">' + responseData.about + '</div>\
                        </section>\
                    </div>\
                </article>';

You can use the ternary operator . In your case, it would be like this:

let resultHTML = '<article class="item">\
                    <div class="post-main">\
                        <header class="clear">\
                            <a href="' + responseData.url + '"</a>\
                            <span class="post-date">just now</span>\
                        </header>\
                        ' + responseData.title ?
                            '<section class="grey">'
                        :
                            '<section class="white">'
                        + '\
                            ' + articleImage + '\
                            <h3>' + responseData.title + '</h3>\
                            <div class="post-about">' + responseData.about + '</div>\
                        </section>\
                    </div>\
                </article>';

I will prefer using Template literals (Template strings) with Conditional (ternary) operator which is more cleaner.

Demo:

 let responseData = {title:'abc'} let articleImage = 'test'; let resultHTML = `<article class="item"> <div class="post-main"> <header class="clear"> <a href=responseData.url </a> <span class="post-date">just now</span> </header> ${ responseData.title ? '<section class="grey">' : '<section class="white">' } ${articleImage} <h3> ${responseData.title} </h3> <div class="post-about"> ${responseData.about} </div> </section> </div> </article>`; console.log(resultHTML);

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