简体   繁体   English

如何显示 HTML 元素的数量等于 JavaScript 数量?

[英]How I can show number of HTML elements is equal to JavaScript number?

I have such function:我有这样的function:

export const getBooksRating = (star) => {
    for(let i = 0 ; ;){
        if(i < star){
            i++
            if(i === star){
                
            }
        }
    }
}

For example star is a number 3 , so how i can return in this situation 3 tags div with some content?例如star是一个数字3 ,那么在这种情况下我怎样才能return带有一些内容的 3 个标签div呢? (i need to return number of div === star ) (我需要返回div === star的数量)

What about something like this?这样的事情呢?

Array(star).fill().map(() => <div></div>)

With some content?有一些内容? Depends on what you mean.取决于你的意思。

This is one solution to return a string of divs:这是返回一串 div 的一种解决方案:

var string;
for(let i = 0; i < star; i++){
  string += "<div id='divid-" + (i+1) + "'>";
}

for(let i = 0; i < star; i++){
  string += "</div>";
}

Output if star == 3: Output 如果星号 == 3:

<div id='divid-1'>
   <div id='divid-2'>
      <div id='divid-3'>

      </div>
   </div>
</div>

If you don't want them to be nested, just use this in the first loop and delete the second:如果您不希望它们嵌套,只需在第一个循环中使用它并删除第二个:

string += "<div id='divid-" + (i+1) + "'></div>";
export const getBooksRating = (star) => {

  const divContent = 'hello world';

  // use string interpolation to put content inside the div
  const content = `<div>${divContent]</div>`

  return content.repeat(star);

}

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

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