【问题标题】:Razor- Giving an 'attribute' to a radioButtonForRazor- 为 radioButtonFor 赋予“属性”
【发布时间】:2020-11-11 07:34:00
【问题描述】:

我有这样定义的单选按钮

 @foreach (var actionType in partActionTypes)
 {
    <td>
         @Html.RadioButtonFor(x => x.Parts[i].SelectedActionType, actionType, new { name = "partRadio" })
    </td>
 }

我尝试将“名称”设置为“partRadio”,(我尝试做 @nameName,但两个选项都不起作用。

在我的 JQuery 代码中,我在单击复选框后克隆了一行, 该代码看起来像这样

 $(document).ready(function () {
            $('.tr_clone input.part-class').change(function () {

                let Id = $(this).attr('id');
                let partId = $(this).attr('data-partId');

                if ($(Id).is(":checked")) {
                    // remove cloned row

                    $("#AllTxt").hide();
                    $("#editQty").show();
                }
                else {
                    var $tr = $(this).closest('.tr_clone');
                    var $clone = $tr.clone();
                    $clone.find('td');
                    $tr.after($clone);
                    $($clone).find(".part-class").hide();
                    $clone.find('input[type="radio"]').attr("name", function (el) { return el.name + 'clone' });
                    $("#AllTxt").show();
                    $("#editQty").hide();               
                }

            });
        });

它应该只是将 'clone' 附加到 'partRadio' 但 HTML 将名称呈现为 'name = undefinedclone`

这是为什么?

【问题讨论】:

    标签: javascript c# html jquery razor


    【解决方案1】:

    问题是因为attr()处理函数的第一个参数是元素的索引,而不是元素本身的引用。

    要解决此问题,您需要使用提供给函数的 second 参数正确接受元素,该参数是 name 属性的当前值:

    $clone.find('input[type="radio"]').attr("name", function (i, n) { 
       return n + 'clone' 
    });
    

    请注意,这可以使用箭头函数缩短:

    $clone.find('input[type="radio"]').attr("name", (i, n) => n + 'clone');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多