javascript - 如果 HTML 包含空格,JQuery HTML 未终止字符串文字错误

标签 javascript c# jquery jquery-ui

通过将其设置为元素的 innerHtml 的一部分,此代码将插入到页面的 HTML 中。它创建一个类似按钮的跨度,单击该跨度时,会打开一个 JQueryUI 窗口,其中包含一些常量文本以及下方的文本“Thiswindow”。

string custom_training_html = "Thiswindow"; // Note this line here.
link = "<span class=\"start_course_button\" onclick=";
link += "javascript:$(\"#temp_test_window\").dialog({minWidth:800,minHeight:600});$(\"#temp_test_custom_html\").html('" + custom_training_html + "');>Test JQueryUI";
link += "</span>\n";

但是,如果我将文本“Thiswindow”更改为“This window”,我会得到:

SyntaxError: unterminated string literal

HTML 中任意位置存在空格都会破坏代码。该网站上的其他问题说问题是 HTML 中的换行符,但我认为我没有任何换行符。我只是构建一个包含 <span> 的字符串代码,工作版本和非工作版本之间的唯一区别是包含空格字符。怎么了?

仅供引用,打开的窗口如下所示:

<div id="temp_test_window" title="Chaucer's Prologue (The Monk)">
    A monk there was, one made for mastery<br />... [snip]
    <div id="temp_test_custom_html">Content Goes Here</div>
</div>

编辑:我已经清理了代码以将 JS 放入其自己的函数中,但这并没有解决问题。在我的主 .aspx 文件中,我有:

function GenerateTestTrainingContent(content)
            {
                $('#temp_test_window').dialog({minWidth:800,minHeight:600});
                $('#temp_test_custom_html').html(content);
            }
[and later, outside the <script> tags:]
<div id="temp_test_custom_html">Content Goes Here</div>

在 .aspx.cs 文件中,我有以下代码创建一些 HTML 作为“链接”:

link = "<span class='start_course_button' onclick=javascript:GenerateTestTrainingContent('OneWord');>";
link += "Test JQueryUI</span>\n";

这有效,给了我一个链接,可以调用弹出的 JQueryUI 窗口,其中显示文本“OneWord”。但是,如果我在同一代码中将“OneWord”更改为“One Word”,我会得到:

SyntaxError: unterminated string literal
javascript:GenerateTestTrainingContent('One

再说一次,没有空格=有效,任何空格=无效。

最佳答案

正如我在评论中提到的,我会将 JS 移至它自己的 <script>堵塞。我还会清理 " 的使用与 '让事情变得不那么困惑。

string custom_training_html = "This window"; // Note this line here.
string link = "";
link += "<span class='start_course_button'>Test JQueryUI</span>\r\n";
link += "<script>\r\n";
link += "$('#temp_test_window').dialog({ autoOpen: false, minWidth:800, minHeight:600 });\r\n";
link += "$('#temp_test_custom_html').html('" + custom_training_html + "');\r\n";
link += "$('.start_course_button').click(function(){ $('#temp_test_window').dialog('open'); });\r\n";
link += "</script>\r\n";

关于javascript - 如果 HTML 包含空格,JQuery HTML 未终止字符串文字错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39708487/

相关文章:

javascript - 按类排列的元素数组 - TypeError : $. id 不是函数

javascript - 我的 html 背景视频无法在 safari 中播放

c# - OpenGL MonoTouch 游戏中的方向

c# - 从服务器上的 SignalR hub 设置 cookie

c# - 使用 Linq 将 Dictionary<String, double> 转换为 Dictionary<String, float>

jquery - 可以将 keyup 绑定(bind)到整个表单吗?

javascript - 在 Javascript 中删除子 div

javascript - 如何在momentjs中显示带有当月和上个月月份名称的动态日期?

javascript - 如何创建 n 个不同的数组,每个数组有 6 个随机数。 - JavaScript/Jquery

javascript - 在变量内执行循环