如何在innerHTML中使用三元条件运算符

问题描述 投票:0回答:2

如何在element.innerHTML中正确使用三元运算符?

el.innerHTML = {
  `<span>title</span>
    ${menuOpened &&
       `<div>
         <span>opened</span>
       </div>`
    }
  `
}
javascript if-statement dom innerhtml conditional-operator
2个回答
0
投票

我认为你不能在另一个`内部字符串模板中使用字符串模板。我可能是错的,但我会使用其他引用来解决它。

el = {};
menuOpened = true
el.innerHTML =
  `<span>title</span>
    ${menuOpened && '<div><span>opened</span></div>' }
  `;
  
console.log(el)  


0
投票

当然,您可以在单行模板中完成此操作,但为了代码的可读性,您可以以经典方式将其拆分为多个步骤,请检查内联注释:

// Set your must have html
let html = `<span>title</span>`;

// Pre-set condition for example purpose
const menuOpened = true;

// Append html if condition is true
if(menuOpened) html += `<div><span>opened</span></div>`;

// Then inner html
// For now we'll just console log it
console.log(html);

但是如果您有更复杂的 html 并且需要插入数据,而不是像您的情况那样添加数据,那么:

// Pre-set condition for example purpose
const menuOpened = true;

// Set code for menu
const menu = menuOpened ? `<div><span>opened</span></div>` : '';

// Set your html template
const html = `<div><span>title</span>${menu}</div>`;

// Then inner html
// For now we'll just console log it
console.log(html);

© www.soinside.com 2019 - 2024. All rights reserved.