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 回答