可以't在<标签>标签

Can't register change handler for radio button inside a <label> tag

本文关键字:标签 gt lt 可以      更新时间:2023-09-26

我目前正在开发一个ASP.NET MVC项目。由于我正在使用的一个组件的限制,我的单选按钮需要放在标签标签内。然而,当我试图在所述单选按钮上注册更改处理程序时,从未调用该处理程序。粗略地看一眼类似的问题,我就悬了。

这是JavaScript代码:

$(document).ready(function () {
    $("input[name=registrationType]").click(function() {
        alert("It works!");
    });
});

这是相关的cshtml:

<div class="radio">
    <label for="registrationType1">@Html.RadioButtonFor(model => model.registrationType, "type1", new { @id = "registrationType1", @required = "required" }) Option 1</label>
</div>
<div class="radio">
    <label for="registrationType2">@Html.RadioButtonFor(model => model.registrationType, "type2", new { @id = "registrationType2", @required = "required" }) Option 2</label>    
</div>

我的问题是,我可以对jQuery代码进行哪些更改来注册更改处理程序?不幸的是,从标签上取下单选按钮不是一种选择,因为我知道这会立即解决问题。

任何帮助都将不胜感激!

编辑:根据要求,这里是呈现的HTML:

<div class="radio">
    <label for="registrationType1"><input class="registrationType" data-val="true" data-val-required="Please indicate your registration type" id="registrationType1" name="registrationType" required="required" type="radio" value="type1" /> Option 1</label>
</div>
<div class="radio">
    <label for="registrationType2"><input class="registrationType" id="registrationType2" name="registrationType" required="required" type="radio" value="type2" />Option 2</label>    
</div>

一种可能的解决方案是将事件处理程序放在父元素上(例如围绕所有单选按钮的<div>)。然后,您可以通过检查event对象的target属性来检测单击的特定元素。这还具有只需要设置一个事件处理程序的优点,这有时更容易编码,也更适合内存管理。

关于在此处检查target属性(包括一些IE兼容性)的更多详细信息:Javascript点击事件处理程序-如何获得对点击项目的引用?

在这里,首先可以方便地解释为什么将事件处理程序放在父级上仍然有效:http://www.quirksmode.org/js/events_order.html