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

标签 javascript html json google-chrome onclick

我是 HTML 和 JS 新手。我正在尝试使用 Chrome 扩展程序将按钮注入(inject)现有页面。我想在单击按钮时提交搜索表单,但目前它在页面加载时提交表单,然后重复提交。我做错了什么?

这是我的 list .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' };

因为当前您的代码执行方式为:

  1. 执行 window.location.href='https://test/search?....c'; 这会立即重新加载您的页面。
  2. 将此执行结果分配给 onclick 处理程序。当您的页面重新加载时,这不会产生任何影响。

关于javascript - Onclick 按钮在页面加载时自动运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49357500/

相关文章:

javascript - 单击添加几行并双击删除添加的行

javascript - Internet Explorer 问题,IE 在 AutoPostBack 后瞬间显示所有可见内容

java - JTextPane.setText(JTextPane.getText()) 清除 HTML 模式下的空白

javascript - 显示模态时未触发 Twitter Bootstrap 模态事件

javascript - react : TypeError: Cannot read property 'name' of undefined

json - 用 Circe 递归替换所有 JSON 字符串值

java - 如何在 Springboot 应用程序中捕获通过 POSTMAN 发送的 JSONObject?

javascript - 我收到一个对象作为响应,我使用 response.json() 将其转换为 JSON,但随后无法从 json 中获取值?

javascript - 随机“被 javascript 拾取

javascript - AngularJS - Controller 应该调用服务还是工厂?