看起来很简单,但我无法弄清楚如何从剃刀代码中调用javascript函数。
问题:我需要在我的表标题中获取一个列的位置,并传递了ID ..我在我的剃刀代码中调用了 getPosition 函数
<table>
<thead>
<tr>
@foreach (Assessment geAssessment in Model.assessments)
{
<th id=@geAssessment.AssessmentID>@geAssessment.Name</th>
}
</tr>
</thead>
<tbody>
<tr>
@foreach (ShortResult geResult in Model.results)
{
@:{ var i = getPosition(@geResult.assessmentId);}
}
</tr>
</tbody>
</table>
我在相同视图/页面中的脚本
<script type="text/javascript">
function getPosition(id) {
var c = '#' + id;
alert(c);
return $c.index();
}
$(function () {});
</script>
更新
根据Max的建议,我改变了我的表格如下,这是完美的,但现在如何在td中设置一个值
<tbody>
<tr>
@{
var index = 4; //start index of assessments will be 4
foreach(Assessment geAssessment in Model.assessments)
{
<td>
@foreach (ShortResult geResult in Model.results)
{
if(geResult.StudentID == geStudent.studentid)
{
@:
<script>
{
var assessmentIndex = getPosition(@geResult.assessmentId);
@*if (assessmentIndex == @index) {
geResult.ResultValue
}*@
}
</script>
}
}
</td>
index++;
}
}
</tr>
</tbody>
现在让我解释一下发生了什么......
每个td我检查我是否有这个特定评估的结果,如果是的话我想在td中打印它...这里有一些语法错误:
if (assessmentIndex == @index) {
geResult.ResultValue
}
答案 0 :(得分:1)
具有getPosition功能的脚本必须高于您的通话。在@之后:你必须使用指令,否则它被视为文本。您的代码必须如下所示:
<script type="text/javascript">
function getPosition(id) {
var c = '#' + id;
alert(c);
return $c.index();
}
$(function () {});
</script>
<table>
<thead>
<tr>
@foreach (Assessment geAssessment in Model.assessments)
{
<th id=@geAssessment.AssessmentID>@geAssessment.Name</th>
}
</tr>
</thead>
<tbody>
<tr>
@foreach (ShortResult geResult in Model.results)
{
@: <script>{ var i = getPosition(@geResult.assessmentId);}</script>
}
</tr>
</tbody>
</table>
答案 1 :(得分:1)
您好,不需要@:语法,您可以直接使用它,所以现在您的代码看起来像。
<script type="text/javascript">
function getPosition(id) {
var c = '#' + id;
alert(c);
return $c.index();
}
$(function () {});
</script>
<table>
<thead>
<tr>
@foreach (Assessment geAssessment in Model.assessments)
{
<th id=@geAssessment.AssessmentID>@geAssessment.Name</th>
}
</tr>
</thead>
<tbody>
<tr>
@foreach (ShortResult geResult in Model.results)
{
<script>{ var i = getPosition(@geResult.assessmentId);}</script>
}
</tr>
</tbody>
</table>