开始阅读“更新”
我有 JavaScript 功能:
<script type="text/javascript">
function getAmount(AdminFee, TimeAndMatRate, TimeSpent, MinimumCharge) {
var amount = math.Round(AdminFee + TimeAndMatRate * TimeSpent);
if (amount < MinimumCharge) {
amount = math.Round(MinimumCharge);
}
document.getElementById('amount').innerHTML = amount;
}
</script>
当我更改另一个值时,我必须更改以下字段:
<span id="amount"></span>
当我更改此文本框中的值时,应更新上述字段:
@Html.TextBoxFor(model => model.TimeAndMaterialsRate, new { onkeyup = "getAmount()" })
只要我不尝试在getAmount()
中发送任何参数,此代码就可以正常工作,但我似乎无法弄清楚如何让它工作,有人可以帮助我吗? / p>
这是我尝试过的事情之一
new { onkeyup = "getAmount("
+ @Model.AdminFee + ","
+ @Model.TimeAndMaterialsRate + ","
+ @Model.TotalTimeSpent.Hours + ","
+ @Model.MinimumCharge + ")"
}
我也试过上面没有&#39; @&#39; s
更新
上面的代码现在可以正常工作,虽然看起来功能没有正常工作。
<script type="text/javascript">
function getAmount(AdminFee, TimeAndMatRate, TimeSpent, MinimumCharge) {
var amount = math.Round(AdminFee + TimeAndMatRate * TimeSpent);
if (amount < MinimumCharge) {
amount = math.Round(MinimumCharge);
}
document.getElementById('amount').innerHTML = amount;
}
</script>
传递给函数的值是id
,id
,double
,id
。关于为什么这不起作用的任何线索?
答案 0 :(得分:1)
我认为你的问题是你的字符串结尾有轻微的语法错误。最后一个加号是在错误的地方。它应该是这样的:
new { onkeyup = "getAmount("+@Model.AdminFee+","+@Model.TimeAndMaterialsRate+","+@Model.TotalTimeSpent+","+@Model.MinimumCharge+")" })
答案 1 :(得分:0)
我说要使用eval,但这是一种不好的不良做法,因为它可以真正注入&amp;东西。
请看这篇文章http://www.sitepoint.com/call-javascript-function-string-without-using-eval/
您需要的是:
// function name and parameters to pass
var fnstring = "runMe";
var fnparams = [1, 2, 3];
// find object
var fn = window[fnstring];
// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);
你的参数看起来像:
var fnparams = {
minimumCharge : '@Model.MinimumCharge',
... // and so on
};
你会以这种方式得到它们:
parseInt(fnparams.minimumCharge);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt