Javascript 单击事件在 Blazor 客户端应用程序中不起作用

som*_*mer 1 javascript asp.net-core blazor blazor-client-side

我是 Blazor 的新手,我创建了一个非常简单的 Webassembly 应用程序。我想要一个 href 链接在我点击它时转到页面下方的 div,但 Javascript 点击事件不起作用。在 Index.razor 页面中,该页面JsRuntime.InvokeVoidAsync("clicker")正在工作并且在alert("In clicker")页面加载时发生,但是单击/href 转到“介绍”div 对爱情和金钱都不起作用:-/

索引.html

<!DOCTYPE html>
<html>
<head>
    <title>My Blazor App</title>
    <!--script type='text/javascript' src='./scripts/app.js'-->
</head>
<body>
    <app>Loading...</app>
    <script src="_framework/blazor.webassembly.js"></script>
    <script>
        function clicker() {
            alert("In clicker"); // this works
            document.getElementById('skip').onclick = function(e){
                alert("clicked"); // this works but the page still won't scroll to the "intro" div :(
            }
        }
        //clicker();
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Index.razor(@code 部分位于页面顶部)

@page "/"
@code {
    [Inject]
    protected IJSRuntime JsRuntime { get; set; }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            JsRuntime.InvokeVoidAsync("clicker");
        }
    }
}

// This link won't go to the intro div when clicked :(
<a id="skip" class="skip" href="#intro">skip this bit</a>
...
<div id="intro" class="home">
...
</div>
Run Code Online (Sandbox Code Playgroud)

启动文件

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IComponentsApplicationBuilder app)
    {
        app.AddComponent<App>("app");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果有人可以对此有所了解,那将节省我的一周。

Mis*_*goo 5

这里不需要 JavaScript。

如果您将特定目标添加到您的标记中,它就会起作用。

您可以使用 target="_top" 来避免Blazor导航拦截。

<a class="skip" href="#intro" target="_top">skip this bit</a>
...
<div id="intro" class="home">
...
</div>
Run Code Online (Sandbox Code Playgroud)

请注意,target="_top"只是指示浏览器在窗口的最顶层框架内导航,并不意味着您将滚动到顶部!