这是怎么了?
var str = "
<div class='lorem'>lorem</div>
<br>
<div class='ipsum'>ipsum</div>
";
$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}
.lorem{
cursor:cell;
background:gold;
}
.ipsum{
cursor:cell;
background:lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
</div>
错误:
Uncaught SyntaxError: Invalid or unexpected token...
lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
答案 0 :(得分:1)
除非使用模板文字,否则字符串中不能包含换行符。
var str = "
<div class='lorem'>lorem</div>
<br />
<div class='ipsum'>ipsum</div>
";
应该是
const str = `
<div class='lorem'>lorem</div>
<br />
<div class='ipsum'>ipsum</div>
`;
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
如果您不想使用此功能(我不知道为什么不使用),也可以执行以下操作:
var str = "<div class='lorem'>lorem</div>" + "<br />" + "<div class='ipsum'>ipsum</div>";
var str = ["<div class='lorem'>lorem</div>", "<div class='ipsum'>ipsum</div>".join("<br />");
var str = `
<div class='lorem'>lorem</div>
<br>
<div class='ipsum'>ipsum</div>
`;
$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}
.lorem{
cursor:cell;
background:gold;
}
.ipsum{
cursor:cell;
background:lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
</div>
答案 1 :(得分:0)
由于字符串是多行的,所以您必须使用字符串串联(+
)或使用Template literals
:
使用模板文字:
var str = `
<div class='lorem'>lorem</div>
<br>
<div class='ipsum'>ipsum</div>
`;
$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}
.lorem{
cursor:cell;
background:gold;
}
.ipsum{
cursor:cell;
background:lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
使用字符串串联(+
):
var str = ""+
"<div class='lorem'>lorem</div>"+
"<br>"+
"<div class='ipsum'>ipsum</div>"+
"";
$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}
.lorem{
cursor:cell;
background:gold;
}
.ipsum{
cursor:cell;
background:lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
</div>
答案 2 :(得分:0)
var str = '<div class="lorem">lorem</div><br><div class="ipsum">ipsum</div>';
$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}
.lorem{
cursor:cell;
background:gold;
}
.ipsum{
cursor:cell;
background:lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
</div>