简体   繁体   English

使用javascript将内容添加到div-“未捕获的SyntaxError:无效或意外的令牌”?

[英]Adding content to div with javascript - 'Uncaught SyntaxError: Invalid or unexpected token'?

I get this error from the code below: 我从下面的代码中收到此错误:

Uncaught SyntaxError: Invalid or unexpected token 未捕获的SyntaxError:无效或意外的令牌

var d1 = document.getElementById('grid');
d1.insertAdjacentHTML('beforeend', '   <figure>
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/placeimg01.jpg" alt="">
    <figcaption>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
    </figcaption>
</figure>');

Jsfiddle 的jsfiddle

The line breaks in the string are causing the issue. 字符串中的换行符引起了问题。 To fix this you could put the string on a single line: 要解决此问题,您可以将字符串放在一行上:

var d1 = document.getElementById('grid');
d1.insertAdjacentHTML('beforeend', '<figure><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/placeimg01.jpg" alt=""><figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</figcaption></figure>');

Updated fiddle 更新的小提琴

Or alternatively you can concatenate it on different lines: 或者,您也可以将其连接在不同的行上:

var d1 = document.getElementById('grid');
d1.insertAdjacentHTML('beforeend', '<figure>' +
    '<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/placeimg01.jpg" alt="">' +
    '<figcaption>' +
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' +
    '</figcaption>' +
'</figure>');

Example fiddle 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM