从代码后面调用时,Javascript函数不起作用

Javascript Function is not working when calling from code behind

本文关键字:Javascript 函数 不起作用 调用 代码      更新时间:2023-09-26

我在.aspx页面中有这个javascript函数。

<script type="text/javascript">
    function somefun(value) {
        document.getElementById("myFlash").SetVariable("player:jsUrl", value);
        document.getElementById("myFlash").SetVariable("player:jsPlay", "");
    }

当我像这样在.aspx页面的正文中称它为时,它非常适合。

<button onclick="somefun('Audio/filename.mp3')">English</button>

但是,如果我在点击事件内后面的代码中调用它,就会出现错误。

protected void theClickEvent(object sender, EventArgs e)
    {
        string filePath1 = "Audio/filename.mp3";
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "Registering", String.Format("somefun('{0}');", filePath1), true);
    }

当我单击按钮时,我会收到以下错误:"无法获取未定义或空引用的属性"SetVariable"

"myflash"调用的对象是

<object id="myFlash" type="application/x-shockwave-flash" data="player_mp3_maxi.swf" width="1093" height="52" >

问题出在哪里?

编辑:

<head runat="server">
<script type="text/javascript">
    function somefun(value) {
        alert(document.getElementById("myFlash"));
        document.getElementById("myFlash").SetVariable("player:jsUrl", value);
        document.getElementById("myFlash").SetVariable("player:jsPlay", "");
    }

<form id="form1" runat="server">
        <asp:LinkButton ID="LinkButton1" Text = "Download"   runat="server" OnClick = "theClickEvent"></asp:LinkButton>         
</form>

<object id="myFlash" type="application/x-shockwave-flash" data="player_mp3_maxi.swf" width="1093" height="52" style="margin-left:0%">
</object>

您正在Button的点击事件中注册JavaScript代码,此时它不会执行代码。

在向脚本管理器注册脚本之前,将执行客户端代码onclick="somefun('Audio/filename.mp3')"

Page_Load中使用您的代码块,而不是按钮单击事件。

更新

Flash对象似乎需要一段时间才能加载,或者在加载之前单击。为了避免这种情况,您可以执行以下操作。

  1. 禁用链接按钮,直到DOM(或JavaScript中的文档)准备就绪
  2. 当DOM/Document准备就绪时,使用JavaScript启用按钮
  3. 此外,在访问元素的任何属性之前进行Null检查也是一种很好的做法

希望这能帮助