[英]JavaScript template: wrap each word in a string in an HTML element
I'm trying to modify a JavaScript template such that each of the words in a particular string are wrapped in <span>
elements. 我正在尝试修改JavaScript模板,以使特定字符串中的每个单词都包裹在<span>
元素中。 I have: 我有:
<% var tagString = "Happy Sad Up Down", tags = tagString.split(" "), wrappedTags = ""; %>
<% for (var i = 0; i < tags.length; i++) { %>
<% wrappedTags += "<span>" + tags[i] + "</span>"; %>
<% } %>
<p><%=wrappedTags%></p>
The problem is that this outputs the "<span>"
and "</span>"
as text, not HTML, so I end up with the following text being displayed on the page: 问题在于这会将"<span>"
和"</span>"
作为文本而不是HTML输出,因此我最终在页面上显示了以下文本:
<span>Happy</span><span>Sad</span><span>Up</span><span>Down</span> <span>快乐</ span> <span>悲伤</ span> <span>上</ span> <span>下</ span>
Is there any way within this syntax to output the wrapping <span>
tags as HTML? 此语法中是否可以将包装的<span>
标签输出为HTML?
UPDATE: with regular (non-template) syntax, it works if I simply write wrappedTags
to the page: http://jsfiddle.net/4QtUd/ . 更新:使用常规(非模板)语法,如果我只是将wrappedTags
页面: http : //jsfiddle.net/4QtUd/ ,它就可以工作。 However, I can't figure out the equivalent way to do this within the template syntax. 但是,我无法在模板语法中找出实现此目的的等效方法。
You could do something like this, outputting it directly within the loop. 您可以执行以下操作,将其直接在循环中输出。
<% var tagString = "Happy Sad Up Down", tags = tagString.split(" "); %>
<p>
<% for (var i = 0; i < tags.length; i++) { %>
<span><%= tags[i] %></span>
<% } %>
</p>
Try replacing your <
and >
with HTML entities. 尝试用HTML实体替换<
和>
。 http://www.w3schools.com/html/html_entities.asp http://www.w3schools.com/html/html_entities.asp
So basically: < -> <
所以基本上: < -> <
and > -> >
和> -> >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.