C# 如何从onchange事件调用javascript中的两个函数
有一个文本框,我只想输入数字,在输入第6个数字时,我想通过单击客户端隐藏按钮的onclick事件(服务器端)调用代码隐藏方法,我想在其中执行一些操作 我面临的问题是,当运行下面的代码示例时,当我在文本框中输入任何数字时,仅调用第一个方法AllowNumericOnly(),而不是调用第二个方法callMethod(),即使在第一个方法返回真值之后也是如此 为什么,我不明白C# 如何从onchange事件调用javascript中的两个函数,c#,javascript,jquery,asp.net,C#,Javascript,Jquery,Asp.net,有一个文本框,我只想输入数字,在输入第6个数字时,我想通过单击客户端隐藏按钮的onclick事件(服务器端)调用代码隐藏方法,我想在其中执行一些操作 我面临的问题是,当运行下面的代码示例时,当我在文本框中输入任何数字时,仅调用第一个方法AllowNumericOnly(),而不是调用第二个方法callMethod(),即使在第一个方法返回真值之后也是如此 为什么,我不明白 <script type="text/javascript"> function callMethod
<script type="text/javascript">
function callMethod()
{
alert('1');
var PinCodeValue=document.getElementById('txtTest').value;
var Pincodelength = PinCodeValue.length;
if(Pincodelength>4)
{
alert('Pincodelength>4');
document.getElementById('Button1').click();
return true;
}
return false;
}
function AllowNumericOnly(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 47 && charCode < 58) || charCode == 8 || charCode == 0)
{
alert('true');
return true;
}
else
{
alert('false');
return false;
}
}
catch (err) {
alert(err.Description);
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtTest" runat="server" MaxLength="7" onkeypress="return AllowNumericOnly(event,this); callMethod();" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" Style="display: none" OnClientClick="alert1();"
OnClick="Button1_Click" />
</div>
</form>
</body>
函数callMethod()
{
警报(“1”);
var PinCodeValue=document.getElementById('txtTest').value;
var Pincodelength=PinCodeValue.length;
如果(Pincodelength>4)
{
警报(“Pincodelength>4”);
document.getElementById('Button1')。单击();
返回true;
}
返回false;
}
函数Allownumeric only(e,t){
试一试{
if(window.event){
var charCode=window.event.keyCode;
}
若否(e){
var charCode=e.which;
}
else{return true;}
如果((charCode>47&&charCode<58)| | charCode==8 | | charCode==0)
{
警报(“真”);
返回true;
}
其他的
{
警报(“假”);
返回false;
}
}
捕捉(错误){
警报(错误描述);
}
}
onkeypress=“if(AllowNumericOnly(event,this))return callMethod();else return false;”最好的方法是创建一个小函数来调用这两个函数,因为它可以改进代码分离
function doBoth(e, t) {
var result = AllowNumericOnly(e, t)
callMethod()
return result;
}
然后您的ASP代码将被读取
<asp:TextBox ID="txtTest" runat="server" MaxLength="7" onkeypress="return doBoth(event, this);" AutoPostBack="true"></asp:TextBox>
您可以使用jquery并将两个事件处理程序绑定到一个元素(按钮)
在上述情况下,两个处理程序都可以工作,jQuery允许以这种方式进行多次调用。。。只要注意火的顺序就行了。请参见创建一个同时调用这两个函数的新函数,onchange然后调用新函数只需使用一个方法,
callMethod()
并从其中调用AllowNumericOnly
。您只能在输入足够的有效字符时调用所有代码。@user3567527:太好了-请随意单击勾号,如果它解决了您的问题,请接受此答案(并可能对答案进行投票)。投票是推动社区的动力:)
$("#txtTest").keypress(function() { AllowNumericOnly(); })
$("#txtTest").keypress(function() { callMethod(); })
$( "#Button1" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
$( "#Button1" ).bind( "click", function() {
alert( "User really clicked on 'foo.'" );
});