Javascript 使用 jQuery 插入多行字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3115360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multi-line string insert using jQuery
提问by Luke Burns
$("#addSelect").click(function() {
$("#optionsForm").after("Hello world.");
} );
This works.
这有效。
$("#addSelect").click(function() {
$("#optionsForm").after("<tr>
<td><input type="text" class="optionField" value="Options" /></td>
<td>
<ul class="option">
<li><select><option>Value..</option></select></li>
</ul>
</td>
</tr>");
} );
Something like this doesn't.
像这样的东西没有。
In Chrome, I get the error "Unexpected token ILLEGAL". After Googling I've discovered my teeny brain doesn't know much about javascript and multi-lines. So I added '\' to then end of each line. Yet, I now get the error "Unexpected identifier".
在 Chrome 中,我收到错误“ Unexpected token ILLEGAL”。谷歌搜索后,我发现我的小脑袋不太了解 javascript 和多行。所以我在每行的末尾添加了'\'。然而,我现在收到错误“意外标识符”。
I'd like this to not be as difficult as I'm making it :)
我希望这不像我做的那么难:)
采纳答案by Glayder Wanderson
Use back ticks ` to start and finish the string
使用反勾号 ` 开始和结束字符串
$("#addSelect").click(function() {
$("#optionsForm").after(`<tr>
<td><input type="text" class="optionField" value="Options" /></td>
<td>
<ul class="option">
<li><select><option>Value..</option></select></li>
</ul>
</td>
</tr>`);
} );
回答by rahul
Change all the double quotes for the attributes to single quotes.
将属性的所有双引号更改为单引号。
$("#addSelect").click(function() {
$("#optionsForm").after("<tr> \
<td><input type='text' class='optionField' value='Options' /></td> \
<td> \
<ul class='option'> \
<li><select><option>Value..</option></select></li> \
</ul> \
</td> \
</tr>");
} );
回答by jpfreire
a cleaner approach is to use <script>tag
更清洁的方法是使用<script>标签
https://stackoverflow.com/a/12097933/1416458
https://stackoverflow.com/a/12097933/1416458
<script id="stuff_you_want" type="text/plain">
<tr>
<td><input type="text" class="optionField" value="Options" /></td>
<td>
<ul class="option">
<li><select><option>Value..</option></select></li>
</ul>
</td>
</tr>
</script>
<script>
// pure javascript
var text = document.getElementById("stuff_you_want").innerHTML ;
//or using jQuery... (document ready for safety)
$(document).ready(function() {
var text = $("#stuff_you_want").html();
}
</script>
content-type must be set for html 4.0 compliance.
必须为html 4.0 合规性设置内容类型。
回答by FabricioG
I prefer to use something like this:
我更喜欢使用这样的东西:
$('<tr bgcolor="#ffffe6"><td></td><td colspan="8" id="orderNotes">'
+ inputNotes.val() + '</td> <td>' + todayStamp
+ '</td> </tr>')
I feel like it's clean the + concatenation allows you to know we're working with the same black and it gives you the flexibility of adding variables.
我觉得它很干净,+ 连接让你知道我们正在使用相同的黑色,它让你可以灵活地添加变量。

