我正在处理一些 Blazor 示例,在尝试使用一些 JSInterop 解决方案时,我遇到了 jQuery UI 元素的问题。我不是一个精通 Javascript 的程序员,但我对 .NET 足够精通,所以我可能会遗漏一些简单的东西。我尝试使用的第一个 jQuery UI 组件是“可调整大小”组件,可在此处找到:https://jqueryui.com/resizable/
这是我当前的代码:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/site.css" rel="stylesheet" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<app>Loading...</app>
<script src="_framework/blazor.server.js"></script>
<script>
$( function() {
$( "#resizable" ).resizable();
});
</script>
</body>
</html>
我确定问题不在于加载库,并且我在加载 blazor.server.js
之后放置了脚本。
现在,我的 Index.cshtml 在 html 部分有以下内容:
<body>
<div class="container-fluid">
<div id="resizable" class="ui-widget-content">
<div class="row row-no-gutters" style="width: 100%; height: 50%">
<h3 class="ui-widget-header">Resizable</h3>
</div>
</div>
</div>
</body>
理想情况下,这会产生可调整大小的 div,但生成的 html 元素不可调整大小。据我了解,Blazor JSInterop 不再需要注册 JS 函数。我做错了什么?
最佳答案
问题在于时间:您的 jQuery 函数在 Blazor 应用呈现之前执行。
我解决这个问题的方法是用我随后调用的命名函数(例如 onBlazorReady
)替换“onready”($(...)
) 函数在正确的时间从我的 Blazor 的 MainLayout
组件。
正确的时间是 OnAfterRender
。
例如:
MainLayout.razor:
@code {
[Inject]
protected IJSRuntime JsRuntime { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
JsRuntime.InvokeVoidAsync("onBlazorReady");
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/site.css" rel="stylesheet" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<app>Loading...</app>
<script src="_framework/blazor.server.js"></script>
<script>
onBlazorReady() {
$("#resizable").resizable();
});
</script>
</body>
</html>
如您所见,我正在注入(inject) IJSInterop
,以便在 LayoutComponent 呈现后调用我的 onBlazorReady
JS 函数。
关于javascript - 如何从 Blazor 组件使用 jQuery UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274629/