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. 上記のシナリオを実装するための最良の方法は何でしょうか?

あなたの提案を共有してください。

JqueryだけでなくMVCもかなり新しいです。

ありがとう

4

1 に答える 1

2

データの取得を容易にするために、コードを少し改善します。

  • idの代わりにclassを使用します(例: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の変更イベントを処理するなど、いくつかのイベントを処理する必要がある場合は、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 に答える