简体   繁体   中英

stopping web page jumping back to top after function call

I am using a ViewBag to pass a List into a View. I am then displaying each string in the list as a href one by one using a foreach over the List. I have a function which allows a user to click on each href to remove it from the list. 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. 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

edit.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>

What happens is after your function is executed, the link with href="#" is triggered. Use event.preventDefault() to prevent that from happening.

 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.

 <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;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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