简体   繁体   中英

JavaScript append HTML in for-loop

in the following snippet I have a for-loop and want to append the HTML Code in each Iteration to use the list inside my ul-Tag. If I replace the += with the = operator it works, but only for the last element obviously. How can I append it correctly in the loop?

    var text = "the Text"
    var list
    for (var i = 1; i < split_respone.length; i+=2) {
      list += <li className="link-list-item">
            <a
            href={split_respone[i]}
            target="_blank"
            rel="noopener noreferrer"
            className="link-list-item-url">
            {split_respone[i+1]}</a>
            </li>
    }
    string = <ul className="link-list">{text}{list}</ul>;
  } 
  const message = self.createChatBotMessage(string);
});
}

You have to set "list" to an empty string for it to work. Additionally, because you are combining strings, you need to enclose the HTML with quotes. (You can also use ``)

    var text = "the Text"
    var list = "";
    for (var i = 1; i < split_respone.length; i+=2) {
      list += '<li className="link-list-item">
            <a
            href={split_respone[i]}
            target="_blank"
            rel="noopener noreferrer"
            className="link-list-item-url">
            {split_respone[i+1]}</a>
            </li>'
    }
    string = <ul className="link-list">{text}{list}</ul>;
  } 
  const message = self.createChatBotMessage(string);
});

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