如何从代码隐藏 (C#) 为 javasctipt 变量赋值?
<script type="text/javascript">
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/, ''); };
function ConstantByCode(_Obj, _Div) {
var pl = new SOAPClientParameters();
_Obj.value = _Obj.value.trim();
pl.add("Code", _Obj.value);
pl.add("Group", _Obj.Grp);
alert(_Obj.Grp);
var _Value = SOAPClient.invoke("ConstantWS.asmx", "GetConstantByCode", pl, false, CallBackEvent);
if (_Value == null || _Obj.value == "" || _Obj.value == null || IsNumeric(_Obj.value) == false) {
_Obj.value = "";
_Div.innerHTML = "";
}
else {
_Div.innerHTML = _Value;
}
}
function CallBackEvent(r) {
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
代码背后
txtCode.Attributes.Add("Grp", Me.ConstValue)
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
txtCode.Attributes.Add("onkeyup", "ConstantByCode(this," & DivTitle.ClientID & ");")
_obj.Grp 现在有值了。 警报说:未定义
最佳答案
我看到您想检索作为自定义属性的 Grp 的值。您需要使用 getAttribute 函数 - 因此您需要使用 _Obj.getAttribute("Grp")
而不是 _Obj.Grp
。
另外,我看到您没有将客户端 ID 括在来自 ode-behind 的引号中。所以不是
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
你要说
txtCode.Attributes.Add("onchange", "ConstantByCode(this,'" & DivTitle.ClientID & "');")
请注意客户端 ID 周围的单引号 (')。
此外,ConstantByCode js 函数似乎正在获取 div 元素。因此,您需要向其中添加一行以将客户端 ID 转换为实际的 DOM。即
function ConstantByCode(_Obj, _Div) {
_Div = document.getElementById(_Div);
.... // rest of the code
关于c# - 在 C# CodeBehind 中为 javascript 变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3655766/