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

时间:2014-09-08 02:26:19

标签: c# javascript asp.net flash

我在.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);
    }

当我点击按钮时,我收到此错误:&#39;无法获取属性&#39; SetVariable&#39;未定义或空引用&#39;

我通过&#34; myflash&#34; 调用的对象是

<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>

1 个答案:

答案 0 :(得分:0)

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

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

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

<强>更新

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

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

    希望这有帮助