简体   繁体   中英

Redirect to Html.ActionLink when click div using jquery

i want to do clickable div and when clicked redirect to Html.ActionLink lockated inside said div.

this is the clickable div jquery

<script language="javascript">
    $(".linkdiv").click(function () {
        if ($(this).find("a").length) {
            window.location.href = $(this).find(".top-menu-link").attr("href");
        }
    });
</script>

and this is how i have written the div:

<div id="top-menu-element" class="linkdiv">
     @Html.ActionLink("Home", "Index", "Home", new { @class = "top-menu-link" })
</div>

i think that the .attr("href") should be something diffrent but i didn't manage to find out what it should be

If the script is in the Razor view, just use:

window.location.href = '@Url.Action("Index", "Home")';

Which Url.Action does the same thing.

<script language="javascript">
    $(".linkdiv").click(function () {
        var anchor = $(this).find("a");
        if (anchor.length) {
            anchor.trigger("click"); 
        }
    });
</script>

Just call the click event for the anchor and use the normal flow of the anchor tag. If this doesn't work try to put this bind click event to the anchor:

$(".linkdiv").find("a").click( function (e) {
  window.location.href = this.href;
});

Or more simple replace:

anchor.trigger("click"); 

With:

anchor.get(0).click();

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