无法在ASP.NET cs页面中调用javascript函数

时间:2022-04-07 08:09:32

I have below JavaScript function in my aspx page:

我的aspx页面中有以下JavaScript函数:

<script>
    function ShowMessage() {
        alert("Hello World");
    }
</script>

I want to use this function in my cs page on button click event:

我想在按钮点击事件的cs页面中使用此功能:

<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />

Now this code works fine:

现在这段代码工作正常:

Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "alert('Hello World');", true);

But this code dose not work:

但是这段代码不起作用:

Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "ShowMessage();", true);

What's wrong in my code? What's the possible reason?

我的代码有什么问题?可能的原因是什么?

3 个解决方案

#1


1  

You need to expose your ShowMessage() function to a scope that your DOM has access to.

您需要将ShowMessage()函数公开给DOM可以访问的范围。

You can try:

你可以试试:

window.ShowMessage = function() {
  alert("Hello World");
}

Another option is to move your <script></script> containing your function ABOVE the DOM element that needs it:

另一种选择是将包含函数的

<script>
  function Foo() {
    alert('Bar');
  }

</script>

<button onclick="Foo()"></button>

#2


1  

You can use onclientclick

您可以使用onclientclick

<asp:Button ID="MyButton" runat="server" Text="Click Here" onclientclick="ShowMessage()" />

#3


0  

Try this:

<script>
    $('#idOfButton').click(
        function() {
            alert("Hello World"); 
        }
    );
</script>

Note: use JQuery for this code and paste this on the end of your HTML page.

注意:对此代码使用JQuery并将其粘贴到HTML页面的末尾。

Hope this will help

希望这会有所帮助

#1


1  

You need to expose your ShowMessage() function to a scope that your DOM has access to.

您需要将ShowMessage()函数公开给DOM可以访问的范围。

You can try:

你可以试试:

window.ShowMessage = function() {
  alert("Hello World");
}

Another option is to move your <script></script> containing your function ABOVE the DOM element that needs it:

另一种选择是将包含函数的

<script>
  function Foo() {
    alert('Bar');
  }

</script>

<button onclick="Foo()"></button>

#2


1  

You can use onclientclick

您可以使用onclientclick

<asp:Button ID="MyButton" runat="server" Text="Click Here" onclientclick="ShowMessage()" />

#3


0  

Try this:

<script>
    $('#idOfButton').click(
        function() {
            alert("Hello World"); 
        }
    );
</script>

Note: use JQuery for this code and paste this on the end of your HTML page.

注意:对此代码使用JQuery并将其粘贴到HTML页面的末尾。

Hope this will help

希望这会有所帮助