简体   繁体   English

如何在 JavaScript 的嵌入式 HTML 中创建 if 语句以显示 CSS 类

[英]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.如何根据 js 数组中是否有数据显示两个类之一。

eg if there is responseData.title show class grey else class white例如,如果有 responseData.title show class gray 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);

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

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