Javascript Onclick按钮在页面加载时自动运行

Javascript Onclick按钮在页面加载时自动运行,javascript,html,json,google-chrome,onclick,Javascript,Html,Json,Google Chrome,Onclick,我不熟悉HTML和JS。我正在尝试将一个按钮插入到一个带有Chrome扩展的现有页面中。我想在单击按钮时提交搜索表单,但此时它会在页面加载时提交表单,然后重复提交。我做错了什么 这是我的manifest.json "browser_action": { "default_icon": "icon.png", "content_scripts" : "script.js" }, "content_scripts": [ { "matches": ["https://test.

我不熟悉HTML和JS。我正在尝试将一个按钮插入到一个带有Chrome扩展的现有页面中。我想在单击按钮时提交搜索表单,但此时它会在页面加载时提交表单,然后重复提交。我做错了什么

这是我的manifest.json

"browser_action": {
"default_icon": "icon.png",
    "content_scripts" : "script.js"
},

"content_scripts": [
  {
    "matches": ["https://test.com/*"],
    "js": ["script.js"],  
    "run_at": "document_end"
  }
这是我的script.js

var button = document.createElement("button");
var buttonName = document.createTextNode("Search By Tag");
  button.appendChild(buttonName);
    document.getElementById("nav-section").appendChild(button).onclick=window.location.href='https://test/search?....c'; 

您需要将处理程序包装到函数中:

document.getElementById("nav-section").appendChild(button).onclick=function() { window.location.href='https://test/search?....c' };
因为当前代码的执行方式是:

  • 执行
    window.location.href=https://test/search?....c';
    将立即重新加载您的页面
  • 将此执行的结果分配给
    onclick
    处理程序。这在重新加载页面时没有任何效果

  • 您需要将处理程序包装到函数中:

    document.getElementById("nav-section").appendChild(button).onclick=function() { window.location.href='https://test/search?....c' };
    
    因为当前代码的执行方式是:

  • 执行
    window.location.href=https://test/search?....c';
    将立即重新加载您的页面
  • 将此执行的结果分配给
    onclick
    处理程序。这在重新加载页面时没有任何效果

  • 您必须在onclick属性中指定一个函数。你可以用下面的方法来做

    var button = document.createElement("button");
    var buttonName = document.createTextNode("Search By Tag");
    button.appendChild(buttonName);
    document.getElementById("nav-section").appendChild(button).onclick = function() {
        window.location.href = 'https://test/search?....c';
    }
    

    您必须在onclick属性中指定一个函数。你可以用下面的方法来做

    var button = document.createElement("button");
    var buttonName = document.createTextNode("Search By Tag");
    button.appendChild(buttonName);
    document.getElementById("nav-section").appendChild(button).onclick = function() {
        window.location.href = 'https://test/search?....c';
    }