0

ユーザーがその場で編集できる入力フィールドを持つ複数のコンテナーを配置できるページを作成しています。現在、私のスクリプトでは、クリック時に入力フィールドをその場で編集できますが、2 つの問題が発生しています。

  1. 各フォームを個別に編集する必要があります。[編集] をクリックすると、他のコンテナのすべてのフィールドも編集可能になります。

  2. キャンセルをクリックすると、何かが入力された場合、何も保存されません。

デモを見る

JQuery

var readonly = true;
$(".edit").on("click", function(e) {
  $('input[type="text"]').attr("readonly", !readonly);
  readonly = !readonly;
  $(".edit").hide();
  $(".button-group").show();
});
$(".save, .cancel").on("click", function() {
  $(".button-group").hide();
  $(".edit").show();
  $('input[type="text"]').attr("readonly", !readonly);
  readonly = !readonly;
});

ありがとうございました!

4

1 に答える 1

1

親要素の親をターゲットにする必要がありthisます。その後、要素を正しくスコープできます。.cancel独自のリスナーに移動し、コードを共有して.cancel.saveリスナーの両方の入力を閉じます。

readonlyまた、属性を保持する必要もありません。簡単に削除できます。完全な例については、以下を参照してください。

var closeInputs = function(selector, type) {
  var parent = $(selector).parent().parent();
  parent.find(".button-group").hide();
  parent.find(".edit").show();
  // loops through each input
  parent.find('input[type="text"]').each(function() {
    // gets the value from the input if 'save', else get the value of the data-value attribute;
    // default to empty string if either is undefined
    var value = (type === 'save' ? $(this).val() : $(this).attr('data-value')) || '';
    // update this input to readonly, set the data-value attribute with a value, then set the input value
    $(this).attr("readonly", true).attr('data-value', value).val(value);
  });
};
$(".edit").on("click", function(e) {
  var parent = $(this).parent().parent();
  parent.find('input[type="text"]').removeAttr("readonly");
  parent.find(".edit").hide();
  parent.find(".button-group").show();
});
$(".save").on("click", function() {
  closeInputs(this, 'save');
  alert('Going to save.');
});
$(".cancel").on("click", function() {
  closeInputs(this, 'cancel');
  alert('Not going to save.');
});

JS フィドル: https://codepen.io/anon/pen/zLWLXM

于 2018-08-01T20:37:58.847 に答える