您需要定位父元素的父元素,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