如何修复JavaScript SyntaxError:无效或意外的令牌错误?

时间:2017-05-05 08:54:44

标签: javascript jquery

我的JavaScript文件中有以下代码:

  input = '<input id="ytRequirementsForm_additional_f__12" type="hidden" value="" name="RequirementsForm[additional][f__12][]" />
    <input class="form-control" name="RequirementsForm[additional][f__12][]" id="RequirementsForm_additional_f__12" type="file" />
<div class="RequirementsForm_additional_f__12 fileprogress" style="display: none"><div class="filename">
                <span class="glyphicon glyphicon-paperclip" aria-hidden="true"></span>
                <strong></strong>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            </div>
            <div class="progress">
                <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="1"
                     aria-valuemin="0" aria-valuemax="100">
                    <span class="percent">0</span>%
                         </div>
            </div>
            <div class="info_danger_text"><p></p></div>
        </div>
        ';

但是,当我运行我的Web应用程序时,它显示未捕获的SyntaxError: Invalid or unexpected token错误。我该如何解决?

3 个答案:

答案 0 :(得分:2)

您只能在ES6中使用多行字符串。要做到这一点,你必须使用反引号字符而不是引号。

请参阅MDN example

答案 1 :(得分:2)

我看到你的&#34;字符串&#34;中有换行符。在JavaScript中,如果要将字符串分配给包含换行符的变量,则应使用&#34; \&#34;在行尾。 以下是更正后的代码。

input = '<input id="ytRequirementsForm_additional_f__12" type="hidden" value="" name="RequirementsForm[additional][f__12][]" />\
<input class="form-control" name="RequirementsForm[additional][f__12][]" id="RequirementsForm_additional_f__12" type="file" />\
<div class="RequirementsForm_additional_f__12 fileprogress" style="display: none">'

我希望它可以帮助你:)

答案 2 :(得分:0)

您应该只在一行中声明字符串变量。如果您想以多行编写,可以通过以下方式进行编写:

  1. 声明用+连接每一行

        input = '<input id="ytRequirementsForm_additional_f__12" type="hidden" value="" name="RequirementsForm[additional][f__12][]" />' +
            '<input class="form-control" name="RequirementsForm[additional][f__12][]" id="RequirementsForm_additional_f__12" type="file" />' +
        '<div class="RequirementsForm_additional_f__12 fileprogress" style="display: none">';

  2. 使用模板文字功能https://css-tricks.com/template-literals/

  3. input = `<input id="ytRequirementsForm_additional_f__12" type="hidden" value="" name="RequirementsForm[additional][f__12][]" />
                <input class="form-control" name="RequirementsForm[additional][f__12][]" id="RequirementsForm_additional_f__12" type="file" />
            <div class="RequirementsForm_additional_f__12 fileprogress" style="display: none">`;