Jquery: Toggle between input and text on click

2019-08-02 14:50发布

I need to toggle between input and text on click. Something like live edit.

I wrote this code, but it doesn't work.

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;
        })    
    }

})

Can someone help me?

2条回答
叼着烟拽天下
2楼-- · 2019-08-02 15:09

Check out this Fiddle. It's not very elegant, but I think it's a quick, cleaner solution than what you were doing. Let me know if you have any more questions.

<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");
    }
});
查看更多
看我几分像从前
3楼-- · 2019-08-02 15:19

First, this.text should be this.innerText or $(this).text().

Second, you need quotes around the value attribute in the <input> tag, or it won't work with multiple words in the value. It would be even better to use the object form of the jQuery element constructor, so that quotes in the value don't cause a problem, either.

Third, the assignment to editmode needs to be outside the replaceWith function. It's after the return statement, so it's never being executed.

Final result:

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

查看更多
登录 后发表回答