【问题标题】:Jquery: Toggle between input and text on clickJquery:单击时在输入和文本之间切换
【发布时间】:2016-11-23 08:35:24
【问题描述】:

我需要在点击时在输入和文本之间切换。类似于实时编辑。

我编写了这段代码,但它不起作用。

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

})

有人可以帮我吗?

【问题讨论】:

标签: jquery html input


【解决方案1】:

看看这个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");
    }
});

【讨论】:

  • 谢谢@joshboley!有用!只有一件事,它需要先显示跨度,然后在点击时显示输入。我只是将输入隐藏在css中,并在输入中写入相同的值。
  • 是的,应该可以的。很高兴我能帮上忙!
【解决方案2】:

首先,this.text 应该是 this.innerText$(this).text()

其次,您需要在&lt;input&gt; 标记中为value 属性加上引号,否则它不适用于值中的多个单词。使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多