You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JQuery启用TextArea编辑功能的问题求助

解决TextArea点击「Editar」按钮无法取消只读的问题

嘿,我一眼就揪出问题所在啦!你的代码里有个超容易忽略的小错误,才导致点击按钮后毫无反应:

核心问题:jQuery选择器写错了

你写的$("tx_justificativa")是在选择标签名为tx_justificativa的元素,但你的TextArea的ID是tx_justificativa,正确的ID选择器必须加上#前缀,也就是$("#tx_justificativa")。

另外,对于readonly这种布尔属性,jQuery官方更推荐用prop()方法来修改,比removeAttr()更可靠——毕竟removeAttr()有时候不会同步元素的属性状态,容易出现“看起来改了但实际没生效”的情况。

修正后的完整代码

我帮你把代码调整好了,还额外加了切换编辑状态的逻辑(点击按钮可以在编辑/只读之间切换,按钮文字也会跟着变,用户体验更顺畅):

@using (Html.BeginForm("SalvarJustificativa", "Riscos")) {
    @Html.AntiForgeryToken()
    <input type="text" name="co_tratamento_risco" id="co_tratamento_risco" value="@item.co_tratamento_risco" hidden />
    <div class="modal-body">
        <div class="md-form">
            <label for="tx_justificativa" class="mb-4 triangulo">Digite sua justificativa:</label>
            @Html.TextArea("tx_justificativa", @item.tx_justificativa, new { @class = "md-textarea form-control", @id = "tx_justificativa", @maxlength = "500", @style = "min-width: 100%", @rows = "5", @readonly = "true" })
        </div>
    </div>
    <div class="modal-footer">
        <button id="btnEditarJust" type="button" class="btn btn-danger mt-4">Editar</button>
        <button id="btnSalvarJust" type="submit" class="btn btn-success mt-4" >Salvar</button>
    </div>
}

<script>
$(document).ready(function () {
    $("#btnEditarJust").click(function () {
        const textarea = $("#tx_justificativa");
        // 切换只读状态
        const isReadonly = textarea.prop("readonly");
        textarea.prop("readonly", !isReadonly);
        // 切换按钮文字,提升交互体验
        $(this).text(isReadonly ? "Cancelar" : "Editar");
    });
});
</script>

为什么这样改?

  • 加上#的ID选择器才能精准定位到你的TextArea元素,这是最关键的修复点
  • 用prop("readonly", false)来取消只读状态,完全符合jQuery对布尔属性的处理规范,不会出现玄学失效
  • 额外添加的切换逻辑让操作更灵活,用户不用反复打开弹窗就能切换编辑状态

内容的提问来源于stack exchange,提问作者Marcos Carvalho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:42:54