简体   繁体   English

使用外部文件使用 javascript 对按钮进行编程

[英]Programming a button with javascript using outer files

Hey guys im trying to program a button in javascript, I called a the button when the button is clicked but it doesnt seem to work.大家好,我正在尝试在 javascript 中编写一个按钮,单击按钮时我调用了按钮,但它似乎不起作用。 any help would be great.任何帮助都会很棒。 Thanks (this is my first time asking a question so please forgive if my format isnt correct. )谢谢(这是我第一次提问所以如果我的格式不正确请原谅。)

// HTML // HTML

<div>
  <button onclick = "page"  > Test button </button>
< /div>

// Javascript // Javascript

function page () {
  <input type="button" onclick="location.href='https://google.com';" 
        value="Go to Google" />
}

You need React to have HTML inside JavaScript in (more or less) the way you wrote it您需要 React 在 JavaScript 中(或多或少)以您编写的方式拥有 HTML

It is also not recommended to have inline event handling (onclick etc)也不建议使用内联事件处理(onclick 等)

You likely mean你可能是说

 window.addEventListener('DOMContentLoaded', function() { // when elements on page are available document.getElementById('page').addEventListener('click', function() { // when button clicked location.href = "https://google.com"; }); });
 <div> <button id="page" type="button">Go to Google</button> </div>

You can do this with just html if you don't want to use react如果你不想使用反应,你可以只用 html 来做到这一点

<button onclick="window.location.replace('https://www.google.com')">
  Click Me
</button>

You can't just use plain HTML inside a vanilla JavaScript function.你不能只在香草 JavaScript function 中使用普通的 HTML。

With plain JS you can assign a DOM element Object to a variable and add an event listener that will trigger the function you create on click:使用纯 JS,您可以将 DOM 元素 Object 分配给一个变量,并添加一个事件侦听器,它将触发您在单击时创建的 function:

    const btn = document.querySelector("button");
   
    function redirectToGoogle () {
       window.location.replace('https://www.google.com')
    }

    btn.addEventListener('click', redirectToGoogle);

ANSWER回答

  1. In HTML file, you didn't call page function on button onclick event.在 HTML 文件中,您没有在按钮 onclick 事件上调用页面 function。
  2. In JavaScript file, location.href is used to locate to another page when you are on the same page.在 JavaScript 文件中,location.href 用于当您在同一页面时定位到另一个页面。

 function page() { location.href = "https://www.google.com/"; }
 <button onclick = "page()" >Test button</button>

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

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