javascript 使HTML按钮运行JavaScript

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 使HTML按钮运行JavaScript相关的知识,希望对你有一定的参考价值。

// 1. We want to get access to the display todos button.
// 2. We want to run displayTodos method when someone clicks the display todos button.

// Make sure your js script is loaded at the end of the html just before the closing <body> tag
// Give the button an id
<button id="displayTodosButton">Display Todos</button>

// Use document.getElementById('displayTodosButton') to get button and place in var
var displayTodosButton = document.getElementById('displayTodosButton');

// Add an event listener to the button for a click
// displayTodosButton.addEventListener('click', function(){});
displayTodosButton.addEventListener('click', function(){
  todoList.displayTodos();
});

//---------------------------------------------------------------
// Refactor to reduce amount of code
// change buttons from:
<button id="displayTodosButton">Display Todos</button>
<button id="toggleAllButton">Toggle All</button>
// to this:
<button onclick="handlers.displayTodos()">Display Todos</button>
<button onclick="handlers.toggleAll()">Toggle All</button>

// and then create an new object for the handlers to keep them organized
var handlers = {
  displayTodos: function(){
    todoList.displayTodos();
  },
  toggleAll: function(){
    todoList.toggleAll();
  }
};
// don't need all of the other code

//-----------------------------------------------------------
// Button and Text Field: get value from text field when clicking button
<button onclick="handlers.addTodo()">Add Todo</button>
<input type="text" id="addTodoTextInput">
// This will run the addTodo() function in the handlers object when clicked
// The id of the input field allows us to use getElementById in the js file.
addTodo: function(){
    var addTodoTextInput = document.getElementById('addTodoTextInput');
    todoList.addTodo(addTodoTextInput.value);
    addTodoTextInput.value = '';
  }
//  

以上是关于javascript 使HTML按钮运行JavaScript的主要内容,如果未能解决你的问题,请参考以下文章

javascript 使HTML按钮运行JavaScript

在 Woocommerce 中将 ajax 添加到购物车事件后运行 javascript 代码

HTML中的Javascript,努力使for循环为按钮工作

概念简介Javas cript简介

如何使 PHP 或 JavaScript 生成 HTML 表单

如何在 Javascript 中使简单的 php 的 foreach 等效? [复制]