在Javascript中处理多行HTML

Handling multi-line HTML inside Javascript

本文关键字:HTML 处理 Javascript      更新时间:2023-11-07

我正在使用Javascript定义网页上的按钮行为。我所追求的行为是在页面的某个地方插入一些新的HTML,但我想使用MVC扩展方法Html.EditorFor来定义将要插入的新HTML。

我想做的是:

$("#myButton").click(function() {
    $("@(Html.EditorFor(x => x.SomeModelProperty))").insertBefore(<somewhere>);
});

我遇到的问题是,调用EditorFor返回的MvcHtmlString呈现为多行HTML,导致Javascript:无效

$("<div>
<label for="ModelData_SomeModelProperty">SomeModelProperty</label>
</div>
<div> ....

在理想的情况下,我可以让EditorFor以某种方式在一行上呈现以上所有内容,或者使用某种特殊的Javascript语法来定义多行字符串(比如在C#中使用单引号),但到目前为止,我还处于空白状态。

我试过调用ToHtmlString并手动编辑生成的字符串以删除换行符,我知道我可以使用/来转义Javascript中的新行,但这样做的问题是,我必须处理转义的HTML,它看起来有点像以下内容:

$("&lt;div&gt;
&lt;label        for=&quot;ModelData_SomeModelProperty&quot;&gt;SomeModelProperty&lt;/label&gt;
&lt;/div&gt;
&lt;div&gt; .... (you get the idea)

我只是想知道是否有人尝试过类似的方法,可能会有更优雅的方法?

一种方法是将其写入html中的隐藏div,而不是直接写入javascript。然后,您可以从dom中读取它,以便在脚本中使用。

所以你的页面会有一个

<div style="display:none" id="hiddenArea">
...insert whatever you want in here 
with newline or whatever...
</div>

然后在您的javascript中:

$("#myButton").click(function() {
    var source = $("#hiddenArea").html();
    $(source).insertBefore(<somewhere>);
});

您可以创建一个HTML帮助程序,以便对返回的内容和格式进行更多控制。

http://www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application