0

表のセルに編集コントロールを追加する機能をきちんとパッケージ化しようとしています。以下は、私が達成しようとしているものの例です。

私が知りたいのは、これが正しい方法であるかどうかです。セルを空にすると、イベント ハンドラーを再バインドする必要があります。jqueryはそれらを削除すると思いますが、確かではありません。ScoreManager オブジェクト内に dom 要素を保存したので、それらが残ることを期待していました。

<div id="main">
 <table id="points-table">
    <thead>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Points</th>
    </thead>
    <tr>
        <td>Joe</td>
        <td>Bloggs</td>
        <td class="points">
            <span>100</span>
            <button>edit</button>
        </td>
    </tr>
    <tr>
        <td>Jiminy</td>
        <td>Cricket</td>
        <td class="points">
            <span>77</span>
            <button>edit</button>
        </td>
    </tr>
 </table>
 </div>

 <script type="text/javascript" src="js/jquery.js"></script>
 <script type="text/javascript">
window.onload = init;

var ScoreManagers = [];

function init() {
    $('#points-table .points').each(function(){
        ScoreManagers.push( new ScoreManager(this) );
    });
}

var ScoreManager = function(cell) {
    this.cell = $(cell);
    this.edit = $('button', this.cell);
    this.points = $('span', this.cell);
    this.scoreInput = $('<input>');
    this.submit = $('<button>Submit</button>');
    this.cancel = $('<button>Cancel</button>');

    this.init();
};

ScoreManager.prototype.init = function() {
    this.edit.bind('click', $.proxy(this.showEditControls, this));
};

ScoreManager.prototype.showEditControls = function(e) {
    this.cell.empty();
    this.cell.append(this.scoreInput, this.submit, this.cancel);
    this.submit.bind('click', $.proxy(this.savePoints, this));
    this.cancel.bind('click', $.proxy(this.cancelEdit, this));
};

ScoreManager.prototype.cancelEdit = function() {
    this.cell.empty();
    this.cell.append(this.points, this.edit);
    this.edit.bind('click', $.proxy(this.showEditControls, this));
}

ScoreManager.prototype.savePoints = function() {
    this.cell.empty();
    this.points.text(this.scoreInput.val());
    this.cell.append(this.points, this.edit);
    this.edit.bind('click', $.proxy(this.showEditControls, this));
}

 </script>
4

2 に答える 2

1

ブラウザーでのイベント委任とイベント バブリングを確認する必要があります。PPK ブログは良い場所です。

次に、エレガントな方法で委任を実装するメソッドのjQuery を見てみましょう。

ここで、DOM に追加された削除されない最上位の要素にイベントをバインドします。それは本体でもあり、必要な要素にデリゲートできます。

$('#points-table').on('click', '.points', function(){
  //what should be done when you click a point element
  });
于 2012-08-26T23:29:30.557 に答える
0

bind要素が削除された後は機能しません。すでに利用可能なすべての要素にイベントを添付しますが、その要素を削除すると、binidng が失われます。新しく追加された要素にもバインディングはありません。すでに存在するか後で追加されるかどうかに関係なく、指定されたセレクターを使用してイベントを要素にバインドできる便利なjQuery.liveを見つけることができます。ただし、最新の jQuery を使用している場合は、廃止されているため、代替手段を使用する必要がある場合があります。また、detach はイベント ハンドラー バインディングを保持するため、.detach()代わりに使用すると便利な場合があります。ただし、子のみではなく、セル全体を削除.empty()するようにコードを変更する必要があります。this.cell.detach();

于 2012-08-26T22:48:09.290 に答える