0

我的视图中有以下代码

<tr id="tblNewContentRow">
       <td>
     @Html.TextBox("txtNewAttributes", "", new { @class = "alphaonly", style = "width: 155px;" })
       </td>
        <td>
      @{@Html.DropDownList("ddlNewValues", Model.OperandsMaxList, new { style = "height: 20px;" })
        }
       </td>
       <td colspan="2">
       @Html.TextBox("txtNewValues", "", new { @class = "numbersonly", style = "width: 250px;" })
    </td>
 </tr>

我为用户添加了按钮,他们可以在其中动态添加他们在运行时想要的 TR(如上所示)。

目前正在使用以下代码使用 JQUERY动态生成TR

var txtNewAttributes = '<td><input type="text" name="txtNewAttributes' + (tblRows + 1) + '"  class="alphaonly" style = "width: 155px;" id="txtNewAttributes' + (tblRows + 1) + '" value="" /></td>';
    var ddlNewValues = '<td><select id="ddlNewValues' + (tblRows + 1) + '" style = "height: 20px;width:75px;" /></td>';
  var txtNewValues = '<td><input type="text" name="txtNewValues' + (tblRows + 1) + '" style = "width: 250px;" id="txtNewValues' + (tblRows + 1) + '" value="" /></td>';
  var repeatRow = txtNewAttributes + ddlNewValues + txtNewValues;
   $('#tblNewSearchAttribute tr:last').prev().after('<tr id="tblNewContentRow' + (tblRows + 1) + '">' + repeatRow + '</tr>');

但是在渲染这些动态行后,我有很多功能要完成。目前,这种使用 dataEntered 的方式有点令人困惑。

我的问题是

  1. 有没有更好的方法可以处理这个问题,以便我可以轻松地将这些数据用于所有功能?
  2. 实现上述方案的最佳方式是什么?

请分享您的建议。

我对 MVC 和 Jquery 都很陌生。

谢谢

4

1 回答 1

2

这是对您的代码的一些改进,以使数据检索更容易:

  • 使用class代替id,例如class='txtAttributes'
  • 应该使用 css 进行样式化,尽可能避免样式化代码。

您的 addNewRow 函数应如下所示:

function addNewRow(){
   var txtNewAttributes = "<td><input type='text' class='txtNewAttributes' /></td>";
   var ddlNewValues = "<td><select class='ddlNewValues'></select></td>";
   var txtNewValues = "<td><input type='text' class='txtNewValues' /></td>";
   var repeatRow = txtNewAttributes + ddlNewValues + txtNewValues;

   $('#tblNewSearchAttribute tr:last').prev().after('<tr class="tblNewContentRow">' + repeatRow + '</tr>');   
}

然后是数据检索函数:

function retrieveData(){
    var items = [];

    // loop for each row
    $("#tblNewSearchAttribute .tblNewContentRow").each(function(){
        var item = {
            txtNewAtribute: $(this).find(".txtNewAttributes").val(),
            ddlNewValues: $(this).find(".ddlNewValues").val(),
            txtNewValues: $(this).find(".txtNewValues").val()
        };
        items.push(item);
    });

    //  return the array of item, each item contains data for a table row
    return items;
}

如果您需要处理一些事件,例如处理表中所有 txtNewValues 的更改事件,您会发现使用 class 而不是 id 更好:

$("'#tblNewSearchAttribute").on("change", ".txtNewValues", function(){
     // do something
});

关于CSS:

#tblNewSearchAttribute .txtNewAttributes {
    width: 155px;
}

#tblNewSearchAttribute .ddlNewValues{
    height: 20px;
    width:75px;
}
于 2013-03-09T08:50:17.720 回答