繁体   English   中英

在 function 调用后停止 web 页面跳回顶部

[英]stopping web page jumping back to top after function call

我正在使用 ViewBag 将列表传递给视图。 然后,我在列表中使用 foreach 将列表中的每个字符串一一显示为 href。 我有一个 function 允许用户单击每个 href 以将其从列表中删除。 问题是,当用户单击 href 以将其从列表和视图中删除时,web 页面会跳回顶部。 有什么办法可以阻止这种情况吗? 例如,当用户单击以从列表中删除 href 字符串时,页面将保持在原来的位置

编辑.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

<script>
    function onDelete(elm, id) {
    // Do something with id
    console.log(id)
    elm.parentNode.removeChild(elm)
}
</script>

在您的 function 执行后会发生什么情况,会触发带有href="#"的链接。 使用event.preventDefault()来防止这种情况发生。

 function myFunction(event, val) { console.log(val); event.preventDefault(); }
 <a href="#" onclick="myFunction(event, 'myValue')">Click me</a>

您需要从锚标记中删除 `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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM