Jquery:单击时在输入和文本之间切换

时间:2014-06-23 23:44:32

标签: jquery html input

我需要在点击时在输入和文字之间切换。像实时编辑一样。

我写了这段代码,但它没有用。

HTML:

<span class="editInput">Change the value on click</span>
<button>Click me</button>

JS:

var editmode = false;

$('button').on('click',function(){
    if(editmode){    
        $('.editInput').replaceWith(function(){
           return '<span class='+this.className+'>'+this.value+'</span>';
           editmode = false;
        })
    }else {
        $('.editInput').replaceWith(function(){
           return '<input type="text" value='+this.text+' class='+this.className+'/>';
           editmode = true;
        })    
    }

})

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

查看此Fiddle。它不是很优雅,但我认为它比你正在做的更快,更清洁。如果您还有其他问题,请与我们联系。

<div>
    <input/>
    <span>test</span>
</div>
<button>Update</button>

span {
    display:none;
}

$('button').on('click',function(){
    if($("input").is(":visible")) {  
        $("input").hide();
        $("span").text(
            $("input").val()
        ).show();
        $("button").text("Edit");
    } else {
        $("span").hide();
        $("input").text(
            $("span").val()
        ).show();
        $("button").text("Update");
    }
});

答案 1 :(得分:0)

首先,this.text应为this.innerText$(this).text()

其次,您需要围绕value标记中<input>属性的引号,否则它不会使用值中的多个单词。使用jQuery元素构造函数的对象形式会更好,因此值中的引号也不会引起问题。

第三,editmode的分配需要在replaceWith函数之外。在return声明之后,它永远不会被执行。

最终结果:

var editmode = false;

$('button').on('click', function () {
    if (editmode) {
        $('.editInput').replaceWith(function () {
            return $("<span>", {
                "class": this.className,
                text: this.value
            });
        });
        editmode = false;
    } else {
        $('.editInput').replaceWith(function () {
            return $("<input>", {
                value: this.innerText,
                    "class": this.className
            });
        });
        editmode = true;
    }

});

FIDDLE