I'm adding a checkbox inside a link with a user-script (Greasemonkey/Tampermonkey/etc.) and I don't want the link to be followed when the checkbox is clicked. This works without any stopPropagation()
or preventDefault()
in Chrome (surprisingly) but I can't get it to work in Firefox.
我尝试了3种方法,下面的简化代码中的理想行为是您可以单击复选框,而不要在``不要去这里''滚动到视图中,但是可以按预期运行复选框,因此可以取消选中并重新选中它等。
In the first approach I do e.stopPropagation()
, this makes the most sense to me and I would expect the click-event to not reach the <a>
element. No dice, Don't go here scrolls into view. The checkbox functions normally, you can uncheck and recheck and I get the .checked
value true
/false
as expected.
In the second approach I changed it to e.preventDefault()
, this stops the link from being followed to the Don't go here-anker but also stops the checkbox from becoming visibly checked. Weirdly, its .checked
property does return true
, but you can't uncheck it, every time you click it it gives true
but doesn't change to a checked checkbox visually.
Lastly, I put a e.preventDefault()
on the onclick of the parentNode
, since it's the parent's default click-behaviour I wanna stop. This yields the same broken checkbox as the second approach.
在MacOS和Windows上的Firefox中进行了测试。如果是这种情况,欢迎任何有识之士,包括“这确实是没有解决方法的Firefox错误”。
Since I'm working on a user-script for an existing web-based tool so I'm somewhat restricted to the HTML that tool gives me. Answers like "don't put the checkbox inside the <a>
" don't help me unfortunately.
let $ = (id) => document.querySelector(id);
$('#stopProp').onclick=function(e) {
e.stopPropagation();
$('#output').value+=this.checked + '\n';
}
$('#prevDef').onclick=function(e) {
e.preventDefault();
$('#output').value+=this.checked + '\n';
}
$('#parentPrevDef').parentNode.onclick=function(e) {
if (e.target.tagName == 'INPUT') {
$('#output').value+='preventing on parent!\t';
e.preventDefault();
}
}
$('#parentPrevDef').onclick=function(e) {
$('#output').value+=this.checked + '\n';
}
a {
display: inline-block;
position: relative;
width: 23%;
border: 1px solid black;
text-align: center;
}
input {
position: absolute;
top: -4px;
left: -5px;
}
textarea, #scroller {
width: 47%;
float: left;
}
#scroller {
height: 2em;
overflow: auto;
}
<a href="#dontgo"><input type="checkbox" id="stopProp"> stopPropagation()</a>
<a href="#dontgo"><input type="checkbox" id="prevDef"> preventDefault()</a>
<a href="#dontgo"><input type="checkbox" id="parentPrevDef"> parent.preventDefault()</a>
<a href="#stay">Reset test</a>
<textarea id="output" rows="10"></textarea>
<div id="scroller">
<a name="stay">Stay here</a><br>
<br>
<a name="dontgo">Don't go here</a>
</div>