简体   繁体   English

如何使用html按钮从.js文件调用函数?

[英]How do I call a function from .js file with a html button?

This is my JavaScript file and I want to use this to mute something in my html file on the press of a button 这是我的JavaScript文件,我想用它来使我的html文件中的内容静音,只需按一下按钮

//checks if its muted or not
var muteCheck = 1;

//function to mute and unmute
function mute() {  
    muteCheck = muteCheck + 1;

    if (muteCheck % 2 === 0) {
        document.getElementById("music").muted = true;
    } else if (muteCheck % 2 === 1) {
        document.getElementById("music").muted = false;
    }
}

This is what my html file looks like 这是我的html文件的样子

<body>

    <audio autoplay loop>
        <source src="audio/something.mp3" id="music">
    </audio>

    <button type="button" id="muteButton" onclick="mute()">mute</button>

    <script src="variablesAndFunctions.js" type="text/javascript">

       mute()

    </script>

</body>

I opened it in Chrome, nothing happens when I press the button, nothing prints in the console or anything. 我在Chrome中打开了它,按下按钮时什么也没发生,控制台上什么也没打印。 I am new to coding so I don't know what I did wrong. 我是编码新手,所以我不知道自己做错了什么。

Any help would be appreciated thanks :D 任何帮助将不胜感激谢谢:D

You are setting muted on the <source> , not <audio> . 您在<source>而不是<audio>上设置了muted The question has been edited but I believe this is the only remaining error. 该问题已被编辑,但我相信这是唯一剩余的错误。

You are toggling the muted property of the <source> element, but this is meaningless. 您正在切换<source>元素的muted属性,但这是没有意义的。

The property applies to the <audio> element. 该属性适用于<audio>元素。

document.getElementById("music").parentNode.muted

That change would help 这种改变会有所帮助

<audio autoplay="autoplay" loop="loop" id="music" >
    <source src="audio/something.mp3" >
</audio>

插入它,它带有静音控件,您无需寻找js

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

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