简体   繁体   English

从Code后面的页面调用Javascript函数

[英]Calling Javascript function from Code behind page

I have a script that I want to pop a window after 5 page views. 我有一个脚本,我想在5页浏览后弹出一个窗口。 The java script works fine on the default.aspx page with a link to call it. java脚本在default.aspx页面上工作正常,并带有一个调用它的链接。 But I want to launce it from my default.aspx.cs page after my session var count gets to 5. How can I do this? 但是我想在会话var count到达5之后从default.aspx.cs页面中将它拉出来。我该怎么做? Is it possible? 可能吗?

default.aspx Default.aspx的

  <script type="text/javascript">
    window.name = "Register";
    function popWin(link) {
        var w = window.open(link.href, link.target, 'width=500,height=600,resizable');
        return w ? false : true; // if popup blocker, use the default behaviour of the link 
    } 
</script>

Default.aspx.cs page Default.aspx.cs页面

 if (Session["PagesViewed"].ToString() == "5")
            {
              //Call my Javascript function How?????

            }

You can output javascript into a LiteralControl from your code behind: 您可以从后面的代码LiteralControl javascript输出到LiteralControl

.aspx: 的.aspx:

<asp:Literal id="myLiteral" runat="server" />

Code behind: 代码背后:

myLiteral.Text = "<script type='text/javascript'>popWin('url');</script>";

When rendered this way, the output script will call the function - make sure it is lower in the page than where the function was defined to ensure it exists. 以这种方式呈现时,输出脚本将调用该函数 - 确保它在页面中比定义函数的位置低,以确保它存在。

In ASP.Net you can do the following: 在ASP.Net中,您可以执行以下操作:

Page.ClientScript.RegisterStartupScript(
    this.GetType(),
    "openpopup",
    "popWin('www.someurl.com');",
    True);

If you need more control over your scripts placement @Oded has a better approach - as trying to call a function that has not been defined isn't a good idea... 如果您需要更多地控制脚本放置@Oded有更好的方法 - 因为尝试调用尚未定义的函数不是一个好主意...

You cannot call javascript functions directly from C#. 你不能直接从C#调用javascript函数。 However, what you could do is pass a <script> to the browser that executes the function. 但是,您可以做的是将<script>传递给执行该功能的浏览器。

response.Write("<script>popWin(something);</script>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM