您好我正在尝试将一块HTML附加到我的页面上的某个类中,但是每当我使用下面的代码时,它似乎会破坏我的整个脚本,而控制台中没有任何错误:
$('.colon1').append("<div id='new-model-slider' class='owl-carousel owl-theme'>
<div class='item'><img src='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/7-SsangYong_Tivoli.jpg' alt='SsangYong Tivoli Red'></div>
<div class='item'><img src='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/12-SsangYong_Tivoli_seating.jpg' alt='Tivoli Seating'></div>
</div>");
我知道在添加HTML时这是不好的做法但是由于特定原因我无法使用AJAX。
知道为什么这个JS可能不会在我的班级中附加?
由于
答案 0 :(得分:6)
在javascript中,如果不使用+
或使用\
以下是一些关于如何做到这一点的例子:
// Example 1
$('.colon1').append("<div id='new-model-slider' class='owl-carousel owl-theme'>\
<div class='item'><img src='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/7-SsangYong_Tivoli.jpg' alt='SsangYong Tivoli Red'>\</div>\
<div class='item'><img src='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/12-SsangYong_Tivoli_seating.jpg' alt='Tivoli Seating'></div>\
</div>");
// Example 2
var string = "";
string += "<div id='new-model-slider' class='owl-carousel owl-theme'>";
string += "<div class='item'>";
string += "<img src='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/7-SsangYong_Tivoli.jpg' alt='SsangYong Tivoli Red'></div>";
$('.colon1').append(string);
//Example 3
$('.colon1').append("<div id='new-model-slider' class='owl-carousel owl-theme'><div class='item'><img rc='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/7-SsangYong_Tivoli.jpg' alt='SsangYong Tivoli Red'></div><div class='item'><img src='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/12-SsangYong_Tivoli_seating.jpg' alt='Tivoli Seating'></div></div>");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="colon1"></div>
&#13;
答案 1 :(得分:2)
执行以下操作
var appendstring = "";
appendstring+="<div id='new-model-slider' class='owl-carousel owl-theme'>";
appendstring+="<div class='item'>";
appendstring+="<img src='/media/wysiwyg/porto/cmspages/ssangyong/tivoli/7-SsangYong_Tivoli.jpg' alt='SsangYong Tivoli Red'></div>";
//and so on ... for the rest of the string ( line by line )
$('.colon1').append(appendstring);
答案 2 :(得分:0)
将您的代码更改为以下内容,删除换行符并使用单引号引用您的html字符串(因为这更自然恕我直言):
$('.colon1').append('<div id="new-model-slider" class="owl-carousel owl-theme"><div class="item"><img src="media/wysiwyg/porto/cmspages/ssangyong/tivoli/7-SsangYong_Tivoli.jpg" alt="SsangYong Tivoli Red"></div><div class="item"><img src=""/media/wysiwyg/porto/cmspages/ssangyong/tivoli/12-SsangYong_Tivoli_seating.jpg" alt="Tivoli Seating"></div></div>');
答案 3 :(得分:0)
您可以在多行上拆分字符串,例如:
var multiStr = "This is the first line" +
"This is the second line" +
"This is more...";
OR
var multiStr = "This is the first line \
This is the second line \
This is more...";
此信息可以帮助您理解。 https://davidwalsh.name/multiline-javascript-strings