我有一个函数,我想从javascript中的一个函数中打印一个html格式的字符串,该函数将字符串中的每个其他字母大写。
javascript:
function crazyCaps(s){
let result =""
for (let i = 0; i < s.length; i++)
if (i%2 == 0){
result += s[i].toLowerCase();
else {
result += s[i].toUpperCase();
}
}
console.log(result);
}
crazyCaps("helloworld");
window.onload = crazyCaps();HTML:
<!DOCTYPE html>
<html>
<head>
<script src ="crazycaps.js" type="text/javascript"></script>
</head>
<body>
crazyCaps();
</body>
</html>发布于 2019-03-02 06:02:03
使用document.body.textContent += result将结果写入页面。而且你不需要有一个window.onload语句,你只需要使用函数:
function crazyCaps(s) {
let result =""
for (let i = 0; i < s.length; i++) {
if (i%2 == 0) {
result += s[i].toLowerCase();
} else {
result += s[i].toUpperCase();
}
}
document.body.textContent += result;
}
crazyCaps("helloworld");<body></body>
发布于 2019-03-02 06:03:31
你的代码中有一些小错误,你不能在html标签之间调用javascript函数。编写crazyCaps();只是以明文形式输出"crazyCaps();“。您需要返回正在创建的字符串,然后将结果赋给html中的一个元素,这可以使用document.getElementById('IDGOESHERE').textContent来完成。if else语句,你需要构造它,以便花括号结束,而else语句开始,if (){} else{},你把else语句放在if语句中。
function crazyCaps(s) {
let result = ""
for (let i = 0; i < s.length; i++)
if (i % 2 == 0) {
result += s[i].toLowerCase();
} else {
result += s[i].toUpperCase();
}
console.log(result);
return result;
}
document.getElementById('crazyoutput').textContent = crazyCaps("helloworld");<body>
<div id="crazyoutput">
</div>
</body>
发布于 2019-03-02 06:04:58
现代的方法是设置一个空的HTML元素作为结果的占位符,然后在需要时填充它。而且,您真的不需要window.onload事件处理程序,只需将<script>移到body元素关闭之前。至此,所有HTML都已解析到DOM中,可以与之交互了。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- JavaScript will access this element and populate it.-->
<div id="results"></div>
<!-- Placing the script just before the closing body tag ensures
that by the time the parser reaches this point, all the HTML
will have been read into memory. -->
<script src ="crazycaps.js" type="text/javascript"></script>
<script>
// Get a reference to the element where the output will go
let output = document.getElementById("results");
function crazyCaps(s){
let result ="";
for (let i = 0; i < s.length; i++){
if (i%2 == 0){
result += s[i].toLowerCase();
} else {
result += s[i].toUpperCase();
}
}
output.textContent = result; // Populate the element
}
crazyCaps("helloworld");
</script>
</body>
</html>
https://stackoverflow.com/questions/54952822
复制相似问题