将JS函数绑定到razor文件中另一个脚本文件中的复选框

时间:2022-04-01 16:00:47

I have a partial razor view containing a textbox like -

我有一个包含文本框的部分剃刀视图 -

@Html.EditorFor(x => x.UnitsBought, new { @onchange = "script.updateUnitPrice(this);" } )

And it is called from main view and the script is referenced like -

它从主视图调用,脚本引用如下 -

$(document).ready(function () {
        let script = new UnitAllocationMaintScript();
        script.initialize();

And the script is in a different JS file like -

脚本在不同的JS文件中,如 -

var UnitAllocationMaintScript = (function ($, app) {
"use strict";
var updateUnitPrice = function (element) {
....
}

But when I change the UnitsBought text box, the error comes up like -

但是当我更改UnitsBought文本框时,出现的错误就像 -

script is undefined.

脚本未定义。

How should I call the function.

我该怎么称呼这个功能。

2 个解决方案

#1


0  

script is defined in the $(document).ready() handler function, so is out of scope of the onchange attribute which runs under the window.

脚本在$(document).ready()处理函数中定义,因此超出了在窗口下运行的onchange属性的范围。

To fix this you could attach the event handler using unobtrusive JS instead of the outdated on* attribute. Try this:

要解决此问题,您可以使用不显眼的JS而不是过时的*属性来附加事件处理程序。尝试这个:

@Html.EditorFor(x => x.UnitsBought, new { @class = "units-bought" } )
$(document).ready(function () {
  let script = new UnitAllocationMaintScript();
  script.initialize();

  $('.units-bought').change(function() {
    script.updateUnitPrice(this);
  });
});

#2


0  

Use unobtrusive event handlers. In other words, don't use HTML attributes like onchange, and instead do:

使用不显眼的事件处理程序。换句话说,不要像onchange那样使用HTML属性,而是:

$('#UnitsBought').on('change', function () {
    ...
});

#1


0  

script is defined in the $(document).ready() handler function, so is out of scope of the onchange attribute which runs under the window.

脚本在$(document).ready()处理函数中定义,因此超出了在窗口下运行的onchange属性的范围。

To fix this you could attach the event handler using unobtrusive JS instead of the outdated on* attribute. Try this:

要解决此问题,您可以使用不显眼的JS而不是过时的*属性来附加事件处理程序。尝试这个:

@Html.EditorFor(x => x.UnitsBought, new { @class = "units-bought" } )
$(document).ready(function () {
  let script = new UnitAllocationMaintScript();
  script.initialize();

  $('.units-bought').change(function() {
    script.updateUnitPrice(this);
  });
});

#2


0  

Use unobtrusive event handlers. In other words, don't use HTML attributes like onchange, and instead do:

使用不显眼的事件处理程序。换句话说,不要像onchange那样使用HTML属性,而是:

$('#UnitsBought').on('change', function () {
    ...
});