JavaScript中的HTML帮助程序? [英] HTML Helper in JavaScript?

查看:85
本文介绍了JavaScript中的HTML帮助程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Razor中,我可以这样做:

In Razor I can do this:

<p @Html.MyCustomDataAttributeFor(person) >@person.Name</p>

要渲染如下内容:

<p data-custom-person-id="1234567890" >Fred</p>

我必须真的这样做(不引人注目)JavaScript:

Must I really then do this in (unobtrusive) JavaScript:

$('p[data-custom-person-id="1234567890"]').css('background-color','red');

当我更喜欢这样做时:

$('p[@Html.MyCustomDataAttributeFor(person)]').css('background-color','red');

如果我可以,否则HTML助手生成的数据属性会发生变化,我的客户端代码将不再设置该元素的样式。

If only I could, otherwise should the data attribute generated by the HTML helper change, my client side code will no longer style the element.

推荐答案

您能将脚本指向.cshtml文件吗?

Could you point the script to a .cshtml-file?

 <script type="text/javascript" src="/myscript.cshtml"></script>

我想我已经为.php和.aspx做了这个,所以我看不到它不应该工作的原因。
在这些情况下,它使服务器首先处理文件。

I think I've done this for both .php and .aspx so I don't see a reason it shouldn't work. In those cases it makes the server first process the file.

否则你可以使用客户 HttpHandler 可解析您想要的任何文字服务器端在发送到客户端之前。

Otherwise you could use a customer HttpHandler that parses whatever text you want server-side before it's sent to the client.

最简单的方法是从Razor设置一些Javascript变量,即:

The easiest however, would be to set some Javascript variables from Razor, ie:

<script type="text/javascript">
    var customerId = '@Html.MyCustomDataAttributeFor(person)';
</script>

然后写:

$('p[' + customerId + ']').css('background-color','red');

这篇关于JavaScript中的HTML帮助程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆