javascript - 如何让我的 HTML 按钮调用我的 Javascript?
问题描述
所以我一直在研究如何解决这个问题,但没有任何效果。我的问题是我试图在 HTML 中创建一个按钮并使用它在我的 javascript 中调用我的函数,但每次我遇到错误或什么都没有发生。
这是我一直在尝试的代码
HTML:
<script type="text/javascript" src="script.js">
</script>
<button onclick= "test1"> test</button>
</html>
Javascript:
onEvent("test1", "click", function( ) {
console.log("message");
});
console.log ("test");
解决方案
您可以将 onclick 属性与函数一起使用:
function test1() {
console.log('message');
}
<button onclick= "test1()"> test</button>
或者动态添加事件监听器:
var button = document.getElementById('button');
button.addEventListener('click', function () {
console.log('message');
});
<button id="button"> test</button>
推荐阅读
- c++ - Getch 不断输出相同的值
- javascript - 在 react.js 中搜索失败时如何返回错误消息
- c# - .wsdl 文件未导入,文件丢失?
- html - 我页面右侧的这个空间来自哪里?
- php - 我在我的 htaccess 文件中添加什么以防止 codeigniter 路由器将请求路由到目录中的页面
- javascript - 将对象显示为列表
- python - 我应该在模型中创建什么关系,以便一个用户只能为产品创建一个评论?
- cumulocity - Unprocessed SigFox Data _ Cumulocity
- oracle - Oracle DBMS_SCHEDULER 错误:ORA-27369。退出代码 7
- java - CrudRepository 通过自定义连接字段过滤器查找