JavaScript按钮点击事件错误解决方法:正确使用函数作为事件处理程序
这个按钮点击不好用是因为在添加点击事件的时候使用了错误的方式。应该使用函数作为事件处理程序,而不是直接执行打开新页面的代码。可以将打开新页面的代码封装在一个函数中,然后将该函数作为事件处理程序传递给按钮的'onclick'属性。修改后的代码如下所示:
// Create a floating button C var buttonC = document.createElement('button'); buttonC.innerHTML = '新开一页面'; buttonC.style.position = 'fixed'; buttonC.style.right = '90px'; buttonC.style.top = '0px'; buttonC.style.zIndex = '9999'; buttonC.style.borderRadius = '3px'; buttonC.style.padding = '5px'; buttonC.style.backgroundColor = '#40B40D'; document.body.appendChild(buttonC);
let countC = 0; // 初始化计数器为0
buttonC.onclick = function() { countC++; // 每次点击按钮,计数器加1 if (countC % 2 === 1) { this.style.backgroundColor = '#40B40D'; // 计数器为奇数,设置背景色为 #cbf43e // 面板位置还原 防止拖动bar无法看到的时候 resetFloatingDivA(); } else { this.style.backgroundColor = '#cbf43e'; // 计数器为偶数,设置背景色为 #40B40D } };
// Define a function to open a new window function openNewWindow() { window.open('http://127.0.0.1:7860/?__theme=dark', '_blank'); }
// Add an event listener to the buttonC for click events buttonC.addEventListener('click', openNewWindow);
原文地址: https://www.cveoy.top/t/topic/owzr 著作权归作者所有。请勿转载和采集!