【问题标题】:Play a song selected from a dropdownlist in ASP.Net播放从 ASP.Net 的下拉列表中选择的歌曲
【发布时间】:2021-09-27 13:54:15
【问题描述】:

我使用 'label1' 像全局变量一样将信息从 1 个脚本 (type="text/javascript") 传递到另一个脚本 (runat="server"),但是 setAttribute("src",.. .) 使用变量似乎不起作用。请注意,如果硬编码,它确实有效。这是我的 ASP.Net 代码的一部分:

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript" >
    var soundObject = null;
    function PlaySound() {
        if (soundObject != null) {
            document.body.removeChild(soundObject);
            soundObject.removed = true;
            soundObject = null;
        }
        soundObject = document.createElement("embed");
        soundObject.setAttribute("src", label1.Text);
        soundObject.setAttribute("hidden", true);
        soundObject.setAttribute("autostart", true);
        document.body.appendChild(soundObject);
    }
    window.onload = PlaySound;
    </script>

    <script runat="server" >    
        void Selection_Change(Object sender, EventArgs e)
        {
            label1.Text = SongList.SelectedItem.Value.ToString();
            Response.Write(SongList.SelectedItem.Value);
        }
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DropDownList id="SongList" AutoPostBack="True" OnSelectedIndexChanged="Selection_Change" 
runat="server">
              <asp:ListItem Selected="True" Value="Love Is All Around.mp3">
Love Is All Around.mp3</asp:ListItem>
              <asp:ListItem Value="Om.mp3">Om.mp3</asp:ListItem>
              <asp:ListItem Value="Nights In White Satin.mp3">
Nights In White Satin.mp3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="label1" Text="Om.mp3" runat="server" />
<input type="button" onclick="PlaySound()" value="Play Sound" />

【问题讨论】:

    标签: asp.net audio drop-down-menu


    【解决方案1】:

    您的问题是,您的 javascript 找不到 label1 变量。

    您不能只在 javascript 中引用 asp.net 服务器控件 - javascript 不知道它们。

    通过带有getElementById 的javascript 找到您的label1,然后读取元素的内容(在javascript 中,这将是span)。您在getElementById 中使用的ID 必须是标签的ClientID,因此如果您想使用label1 作为id,则需要将ClientIDMode 属性设置为static。

    【讨论】:

    • 谢谢,成功了。注意我不需要跨度。我只是: var song = document.getIdByElement("label1); 并将 setAttribute 从 label1.Text 更改为 song.InnetText。最后,在定义 label1 的地方,我添加了 ClientIdMode="static" 属性。
    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 2016-07-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多