jquery JavaScript错误,因为输入意外结束

yhxst69z  于 2023-03-01  发布在  jQuery
关注(0)|答案(1)|浏览(173)

我试图保存我的文件,但在附加默认的HTML基本结构时出错。

$('#saveHTML').click(function() {
    var html = $('#editor').val();
    // Append the default HTML base structure
    html = `<!DOCTYPE html><html><head><title>HTML File</title></head><body>' + html + '</body></html>`;
    // Write your code to save HTML file here.
    // Generate a random filename
    var filename = Math.random().toString(36).substr(2, 9);
    // Create a temporary element
    var tmpElement = document.createElement('a');
    // Set temporary element attributes
    tmpElement.download = filename + '.html';
    tmpElement.href = 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
    // Simulate click on the temporary element
    tmpElement.click();
    // Remove the temporary element
    document.body.removeChild(tmpElement);
    // Show success message
    alert('HTML file saved successfully!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="editor"></textarea>
<button id="saveHTML">Click</button>

我做错了什么?
我收到以下错误:
未捕获的语法错误:第3行输入意外结束 *

hyrbngr7

hyrbngr71#

我发现了两个错误:
1.尝试使用模板字符串和字符串连接时出错。正确用法显示在第4行。
1.您忘记将a标记附加到主体。请参见第10行。祝您好运!

$('#saveHTML').click(function() {
    var html = $('#editor').val();
    // Append the default HTML base structure
    html = `<!DOCTYPE html><html><head><title>HTML File</title></head><body>${html}</body></html>`;
    // Write your code to save HTML file here.
    // Generate a random filename
    var filename = Math.random().toString(36).substr(2, 9);
    // Create a temporary element
    var tmpElement = document.createElement('a');
    document.body.appendChild(tmpElement);
    // Set temporary element attributes
    tmpElement.download = filename + '.html';
    tmpElement.href = 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
    // Simulate click on the temporary element
    tmpElement.click();
    // Remove the temporary element
    document.body.removeChild(tmpElement);
    // Show success message
    alert('HTML file saved successfully!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="editor"></textarea>
<button id="saveHTML">Click</button>

相关问题