[英]stopping web page jumping back to top after function call
I am using a ViewBag to pass a List into a View.我正在使用 ViewBag 将列表传递给视图。 I am then displaying each string in the list as a href one by one using a foreach over the List.
然后,我在列表中使用 foreach 将列表中的每个字符串一一显示为 href。 I have a function which allows a user to click on each href to remove it from the list.
我有一个 function 允许用户单击每个 href 以将其从列表中删除。 The problem is, when a user clicks a href to remove it from the list and from the view, the web page jumps back to the top.
问题是,当用户单击 href 以将其从列表和视图中删除时,web 页面会跳回顶部。 Is there any way I can stop this?
有什么办法可以阻止这种情况吗? eg when a user clicks to remove a href string from the list, the page stays where it is
例如,当用户单击以从列表中删除 href 字符串时,页面将保持在原来的位置
edit.cshtml编辑.cshtml
<div class="form-group" style="min-height: 100px">
<div class="col-md-10" style="min-height: 100px">
<hr />
<p><strong>Flagged Questions</strong></p>
@foreach (var item in ViewBag.FLagList)
{
<div>
<a href="#" onclick="this.parentNode.parentNode.removeChild(this.parentNode)">@item</a>
</div>
}
</div>
</div>
function function
<script>
function onDelete(elm, id) {
// Do something with id
console.log(id)
elm.parentNode.removeChild(elm)
}
</script>
What happens is after your function is executed, the link with href="#"
is triggered.在您的 function 执行后会发生什么情况,会触发带有
href="#"
的链接。 Use event.preventDefault()
to prevent that from happening.使用
event.preventDefault()
来防止这种情况发生。
function myFunction(event, val) { console.log(val); event.preventDefault(); }
<a href="#" onclick="myFunction(event, 'myValue')">Click me</a>
you need to remove the `href attribute from the anchor tag and then you can give custom css for the anchor to restore the missed styles due to removing the href att.您需要从锚标记中删除 `href 属性,然后您可以为锚提供自定义 css 以恢复由于删除 href att 而丢失的 styles。
<a class='custom-link' onclick="this.parentNode.parentNode.removeChild(this.parentNode)">@item</a>
.custom-link:link {
background-color: yellow;
}
.custom-link:visited {
background-color: cyan;
}
.custom-link:hover {
background-color: lightgreen;
}
.custom-link:active {
background-color: hotpink;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.