我一直收到一个未终止的字符串文字错误

时间:2012-04-07 19:56:27

标签: javascript

它不断给我一个未终止的字符串文字错误但我无法看到问题。如何在下面修复:

 var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload();' >
    <p class='f1_upload_process'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='f1_upload_form'><br/><label>
    File: <input name='fileImage' type='file' class='fileImage' /></label><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>
    </p> <iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe></form>");

$image.append($fileImage);

1 个答案:

答案 0 :(得分:4)

JavaScript不是PHP。字符串中不允许换行符。

在每行末尾添加\,或使用" + "连接字符串。

// Using \, scroll to the right to see how to use it
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload();' >\
    <p class='f1_upload_process'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='f1_upload_form'><br/><label>\
    File: <input name='fileImage' type='file' class='fileImage' /></label><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>\
    </p> <iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe></form>");

// Using string concatenation
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload();' >" + 
    "<p class='f1_upload_process'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='f1_upload_form'><br/><label>" + 
    "File: <input name='fileImage' type='file' class='fileImage' /></label><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>" +
    "</p> <iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe></form>");

由于你使用的是 jQuery ,我建议使用jQuery创建可读和可维护的代码:

var $form = $('<form>', {
    action: 'upload.php',
    method: 'post',
    enctype: 'multipart/form-data',
    target: 'upload_target'
}).submit(startUpload);
// Et cetera.