[英]Reacting to changes in radio button on the client side of a Razor ASP.NET Core Page
I am trying to make a radio button on an ASP.NET Core Razor page control the appearance of another UI element without requiring a roundtrip to the server.我正在尝试在 ASP.NET Core Razor 页面上创建一个单选按钮来控制另一个 UI 元素的外观,而无需往返服务器。
Here is an example of what I am trying to do, but with a roundtrip to server.这是我正在尝试做的一个示例,但需要往返服务器。
Running program looks like this:运行程序如下所示:
Here is the relevant code:这是相关的代码:
// Test.cshtml
<h3 style="color:@Model.Color">Hello in @Model.Color</h3>
<form method="post">
<input type="radio" asp-for="Color" value="red" />Red<br />
<input type="radio" asp-for="Color" value="green" />Green<br />
<input type="radio" asp-for="Color" value="blue" />Blue<br />
<input type="submit"/>
</form>
// Test.cshtml.cs
public class TestModel : PageModel {
[BindProperty]
public string Color { get; set; }
public async Task<IActionResult> OnGetAsync() {
return Page();
}
}
In order for the text to change color, end-users must click [Submit];为了使文本改变颜色,最终用户必须单击[提交]; I would like to avoid it.我想避免它。 Please suggest a client-side solution.请提出一个客户端解决方案。
Since this will be done client-side, you can use javascript.由于这将在客户端完成,您可以使用 javascript。
document.querySelector
and document.querySelectorAll
are used to select elements from the DOM and operate using CSS style selectors. document.querySelector
和document.querySelectorAll
用于从 DOM 中选择元素并使用 CSS 样式选择器进行操作。 Select the radio
buttons and add an onclick
event to each.选择radio
按钮并为每个按钮添加一个onclick
事件。 In the onclick
event update the h3
style and text.在onclick
事件中更新h3
样式和文本。
The below snippet uses plain javascript.下面的代码段使用普通的 javascript。 jQuery is another great tool I'd recommend for this kind of task. jQuery是我为此类任务推荐的另一个很棒的工具。
var radios = document.querySelectorAll('input[type=radio]'); for (radio in radios) { radios[radio].onclick = function() { var h3 = document.querySelector('h3'); h3.style.color = this.value; h3.innerText = 'Hello in ' + this.value; } }
<h3 style="color:@Model.Color">Hello in @Model.Color</h3> <input type="radio" asp-for="Color" value="red" />Red<br /> <input type="radio" asp-for="Color" value="green" />Green<br /> <input type="radio" asp-for="Color" value="blue" />Blue<br />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.