[英]adding style to items in an array
我正在做一个madlibs型程序。 提示要求输入单词,然后将其添加到字符串中。 我希望将提示中使用的单词与字符串的其余部分一起显示时加下划线。 我已经创建了一个包含所有提示的数组。 现在,我只需要知道如何遍历该数组并将文本修饰更改为“下划线”即可。 我知道我需要在数组中使用for循环,但是不确定如何处理它。
做到这一点的最佳方法是什么?
HTML:
<body>
<div id = "story-space">
</div>
<script src = "madlibs.js"></script>
</body>
JS:
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3, prompt4];
var text = "There was once was a " + prompt1 + " from " + prompt2 + " who liked to " + prompt3 + "."
document.getElementById("story-space").innerHTML = text;
为什么要添加这样的html样式
var text = "There was once was a <span style='text-decoration:underline'>" + prompt1 + "</span> from <span style='text-decoration:underline'>" + prompt2 + "</span> who liked to <span style='text-decoration:underline'>" + prompt3 + "</span>."
您可以通过使用下划线类映射所有提示来尝试类似的操作。
var prompt1 = prompt("Enter a animal."); var prompt2 = prompt("Enter a city."); var prompt3 = prompt("Enter an activity."); var prompts = [prompt1, prompt2, prompt3]; prompts = prompts.map(prompt => `<span class="underline">${prompt}</span>`) var text = "There was once was a " + prompts[0] + " from " + prompts[1] + " who liked to " + prompts[1] + "." document.getElementById("story-space").innerHTML = text;
.underline { text-decoration: underline; }
<div id = "story-space"> </div>
您还可以尝试如下所示的操作,在该操作中只需提供提示的前缀,然后让Map
and Reduce
完成其余工作。
let textPromptMap = new Map(); textPromptMap.set("There was once was a ", prompt("Enter a animal.")) textPromptMap.set(" from ", prompt("Enter a city.")) textPromptMap.set(" who liked to ", prompt("Enter an activity.")) const text = [...textPromptMap.keys()] .reduce((a, b) => `${a}${b}<span class="underline">${textPromptMap.get(b)}</span>`, "" ) document.getElementById("story-space").innerHTML = text;
.underline { text-decoration: underline; }
<div id = "story-space"> </div>
一种简单的操作方法如下,请注意,尽管如此,您需要检查从提示符返回的空字符串,但此答案中未对此进行处理,
var questions = ['an animal', 'a city', 'an activity'],
answers = [];
// create source string with placeholders that
// can be replaced with values in from prompts
var sourceText = "There was once was a {0} from {1} who liked to {2}."
//loop thru questions array and store answers in 'answers' variable
for (var q = 0; q < questions.length; q++) {
//create answer as span element
var question = questions[q],
answer = '<span style="text-decoration:underline;">';
answer += prompt('Enter ' + question);
answer +='</span>';
//update source text's 'qth' placeholder with answer
sourceText = sourceText.replace( new RegExp( "\\{" + q + "\\}", "g" ), function() {
return answer;
});
}
//update the target element's innerHTML
document.getElementById("story-space").innerHTML = sourceText;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.