【问题标题】:Edit in-place multiple input fields就地编辑多个输入字段
【发布时间】:2018-08-01 20:16:13
【问题描述】:

我正在构建一个页面,用户可以在其中放置多个带有可就地编辑的输入字段的容器。我目前的脚本允许我在点击时编辑输入字段,但我遇到了 2 个问题:

  1. 我需要单独编辑每个表单。在点击编辑的那一刻,其他容器中的所有字段也都可以编辑了。

  2. 单击取消时,如果输入了任何内容,则不应保存任何内容。

See DEMO

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;
});

谢谢!

【问题讨论】:

    标签: jquery forms input edit-in-place


    【解决方案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

    【讨论】:

    • 我注意到,如果您键入内容并单击取消,它仍然会保存它。除此之外一切似乎都很好。谢谢。
    • 是的,您可以清除取消侦听器上的值。现在很容易做到。
    • 我不太清楚该怎么做。我试过使用 $('input[type="text"]').val(null);在取消侦听器中,但这会清除整个输入字段。抱歉,我不太擅长 JQuery。
    • $(this).parent().parent().find('input[type="text"]').val(''); 添加到上述答案中。
    • 如果您输入内容并保存,然后编辑相同的输入字段,只需在您之前输入的内容中添加更多文本。然后按取消,一切都会被清除,它应该只清除添加的新文本。我希望这是有道理的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多