我有一个带有表和表格的HTML页面。当我在行上klick时,它应该打开一个细节页面,但是当我单击表格时,不应触发此内容。
我的行看起来像这样:
<tr onclick="window.parent.location.href='details.php?id=123';"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onsubmit="return confirm('Are you sure?');">
</form>
</td></tr>
因此,它应该像这样工作:如果我在尺寸范围内或在提交按钮上,则不应调用细节页。
我发现一个人可以使用event.stoppropagation((,但是我无法找到如何使用普通JavaScript进行操作,尽管似乎应该有一个简单的解决方案
尝试
<tr onclick="window.parent.location.href='details.php?id=123';">
<td><img /></td>
<td>text</td>
<td>price<br>
<form method="post" onsubmit="return confirm('Are you sure?');">
<input type="number" name="size" value="1" onclick="event.stopPropagation()">
<input type="submit" onclick="event.stopPropagation()">
</form>
</td>
</tr>
注意:从input
元素中删除OnSubmit,然后将其添加到形成元素。谢谢@epascarello的更正。
这是解决方案
<tr onclick="var x = event.clientX;var y = event.clientY;if(document.elementFromPoint(x, y).tagName.toLowerCase()!='input'){window.parent.location.href='details.php?id=123'; }"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onclick="return confirm('Are you sure?');">
</form>
</td>
</tr>
我本人遇到了这个问题,这篇文章帮助了我:如何停止从父母div到Child Div
的传播事件因此,您需要设置这样的东西:
var parent = document.getElementsByClassName("parent")[0];
var child = document.getElementsByClassName("child")[0];
parent.addEventListener("click", function(e) {
alert("you clicked parent");
if (e.target !== this) {
return;
}
e.stopPropagation();
// parent.style.color = "green";
});
child.addEventListener("click", function(e) {
alert("you clicked child");
if (e.target !== this) {
return;
}
e.stopPropagation();
});
.parent {
width: 500px;
height: 500px;
background-color: red;
}
.child {
width: 200px;
height: 200px;
background-color: blue;
}
<div class="parent">
<div class="child">
</div>
</div>
在您的情况下,也许尝试包含一个带有函数的脚本以呼吁onclick元素属性以获得更好的可读性:
<tr onclick="changeLocation(e, 'details.php?id=123')"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onclick="return confirm('Are you sure?');">
</form>
</td></tr>
<script>
function changeLocation(e, reference) {
if (e.target !== this) {
return;
}
e.stopPropagation();
window.parent.location.href=reference;
}
</script>
甚至更好的传播事件功能:
<tr onclick="stopProp(this); window.parent.location.href='details.php?id=123';"><td><img /></td><td>text</td><td>price<br>
<form method="post">
<input type="number" name="size" value="1">
<input type="submit" onclick="stopProp(this); return confirm('Are you sure?');">
</form>
</td></tr>
<script>
function stopProp(e) {
if (e.target !== this) {
return;
}
e.stopPropagation();
}
</script>
谢谢大家 - 我使用了sanketd617的解决方案,它效果很好 - 对不起,对于onsubmit的错误 - 在我的文件中,它在-tag中 - 我键入了它,但没有键入复制/粘贴代码,因为我的代码更为复杂。
我也尝试了Aricha的代码,但对我不起作用 - 它仍然执行了细节页面,但也许我在那里也犯了一个错误。我以前尝试过类似的解决方案,但它从未对我有用。
,但我没有在输入元素的ONCLICK中找到非常简单的解决方案。所以非常感谢