親要素の親をターゲットにする必要があり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