我有一个复制2-3 div的代码,div包含一个只读属性。
在此之后,我有一个按钮,当我单击该按钮时,该按钮表示要编辑,这将删除readonly,并且输入字段可用于编辑。
我的代码不起作用!
我的javascript代码:
我试过removeAttr,prop('readonly', false),attr('readonly', false)
$("body").on("click", ".btn",function(){
if($(this).is("#edit")){
$(this).parents(".control-group").removeAttr('readonly');
}else if($(this).is("#save")){
}else if($(this).is("#remove")){
$(this).parents(".control-group").remove();
}
});我复制的div:
<div class="control-group input-group" style="margin-top:10px">
<input id="rule" type="text" class="form-control" readonly>
<div class="input-group-btn">
<button id="edit" class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Edit</button><button id="remove" class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>我希望,当我点击编辑只读消失后,点击保存和再读回来。
谢谢你的帮助
PS:删除按钮工作!
发布于 2019-07-29 22:43:52
.attr的运气可能会更好,因为readonly是attribute,而不是property。参见这 (特别是属性与属性)
我在您的代码中看到的一个问题是这里的一行:$(this).parents(".control-group").removeAttr('readonly');
您正在尝试从div中移除只读属性。我想你是想把它从你的.form-control中删除,这是一个input
也许可以试试$(this).parents(".control-group").find('input.form-control').removeAttr('readonly'); (我会在这里做一些空检查。如果选择器失败,很多都会出错)
下面是如何使用readonly切换jQuery属性的基本示例
var readonly = true;
$('button').on('click', (e) => {
readonly = !readonly
$('input').attr('readonly', readonly);
// Extra
if (readonly) {
$('input').attr('placeholder', "I'm readonly");
} else {
$('input').attr('placeholder', "I'm not readonly");
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input readonly placeholder="I'm readonly" />
<button>Toggle Readonly</button>
发布于 2019-07-29 23:17:16
您将remove应用于错误的元素。
试试这个:
$("body").on("click", ".btn",function(){
if($(this).is("#edit")){
$(this).parents(".control-group").find('input').removeAttr('readonly');
}
...
}
});使用find jQuery函数,可以调用.control-group元素中的每个输入元素。要进一步扩展功能,例如,包括select元素或其他按钮(例如,使用unlock-readonly类),您可以尝试:
$(this).parents(".control-group").find('input, select, .unlock-readonly').removeAttr('readonly');https://stackoverflow.com/questions/57262173
复制相似问题