Tampermonkey脚本生成的按钮链接在Chrome可用,Firefox点击无响应?
问题原因及解决方案
这问题我之前帮朋友排查过,核心问题是你写的HTML结构违反了HTML规范——<button>元素内部是不允许嵌套<a>标签的!不同浏览器对这种非法嵌套的容错处理不一样,这就是为什么Chrome能正常点击,Firefox不行。
具体原因
Chrome的HTML解析器会自动修正这种错误结构,比如可能把<a>标签从<button>里“拉出来”,或者让<a>的点击事件优先生效;但Firefox的解析逻辑更严格,它会保留你写的错误嵌套结构,导致<a>的点击行为被<button>的默认表单提交行为(你写了type="submit")覆盖,或者<a>根本没有被正确识别为可点击元素。
两种修复方案
方案1:用<a>标签模拟按钮(推荐,兼容性最好)
直接去掉<button>,给<a>加按钮样式,这样既符合HTML规范,又能在所有浏览器正常跳转:
var html = '<div id="gmSomeID"><a id="tapButton" href="' + output_url + '" style="color:white; display: inline-block; padding: 8px 16px; border: none; border-radius: 4px; background-color: #0066cc; text-decoration: none; cursor: pointer;">A</a></div>'; $("body").append(html);
方案2:给<button>绑定点击事件跳转
如果一定要用<button>,就不要嵌套<a>,而是通过JavaScript绑定点击事件来实现跳转:
// 创建按钮元素 var $button = $('<button id="tapButton" type="button" style="color:white; padding: 8px 16px; border: none; border-radius: 4px; background-color: #0066cc; cursor: pointer;">A</button>'); // 绑定点击跳转事件 $button.on('click', function() { window.location.href = output_url; }); // 添加到页面 $('<div id="gmSomeID"></div>').append($button).appendTo('body');
注意这里把type="submit"改成了type="button",避免按钮触发不必要的表单提交行为。
内容的提问来源于stack exchange,提问作者NickP
相关产品推荐
相关产品推荐

