使用 jQuery 将标签更改为空文本框

change label to a Empty textbox by using jQuery

我想使用 Jquery 函数将标签替换为空文本框。下面是我工作过的代码。

<label>Label1</label><br />
<input type="button" value="Edit" id="Edit" />
$( "#Edit" ).click( function() {
    $( "label" ).replaceWith( function() {
        return "<input type=\"text\" value=\"" + $( this ).val("") + "\" />";
    });
});

Link

标签没有与之关联的值 属性。您需要使用 .text() 而不是 .val() 来获取文本内容:

$( "#Edit" ).click( function() {
    $( "label" ).replaceWith( function() {
        return "<input type=\"text\" />";
    });
});

Working Demo

与价值相关的第一条规则。试试 .val() .value 和 .text()。然后如果他们都失败了,再深入挖掘。

$( this ).text()

将为您获取当前值。

但我的建议是废弃输入并添加:

<label contenteditable="true">Label1</label>

您可以试试下面的代码:

<label id="labelId">Label1</label><br />
<input type="button" value="Edit" id="Edit" />
<script type="text/javascript">
    $("#Edit").click(function () {
        $("Label#labelId").replaceWith(function () {
            return "<input type='text' value='' />";
        });
    });
</script>

希望这对您有所帮助:)

基于此.replaceWith(...) and .prev(...), even .clone(...) and .replaceAll(...),您可以...

$('#Edit').on('click', function()
{
    // IF YOU WANT TO REPLACE BY THE CURRENT INPUT
    $(this).prev('label').replaceWith(this); // see that I ensure the previous element is a labal
    // ELSE
        // IF YOU WANT KEEP EVENT HANDLERS
        $(this).clone(true).replaceAll($(this).prev('label'));
        // ELSE
        $(this).clone().replaceAll($(this).prev('label'));
        // FI
    // FI
})

return "<input type=\"text\" />";

DEMO

像这样 return 以便输入为空您还可以添加 ID 或 Class 以便稍后在需要时参考输入,如下所示

return "<input type=\"text\" class=\"classname\"/>";