[英]Changing input to div and vice versa
I've got some code to change input into div's 我有一些代码可以将输入更改为div
$(document).ready(function(){
$('#btnChange').click(function(){
$('#products, #mrp, #discount').replaceWith(function(){
return '<div id="'+this.id+'">'+this.value+"</div>";
});
});
});
What I want is to change them back on Second Click of the button from div to input with same id's and the same value. 我想要的是在div的第二次单击按钮时更改它们以输入相同的id和相同的值。 Or you could say undo what I did on first click.
或者你可以说撤消我在第一次点击时所做的事情。
Try 尝试
$(document).ready(function () {
$('#btnChange').click(function () {
$('#products, #mrp, #discount').replaceWith(function () {
if ($(this).is('input')) {
return $('<div />', {
id: this.id,
//use text to prevent html injection
text: this.value
});
} else {
return $('<input />', {
id: this.id,
value: this.innerHTML
});
}
});
});
});
You can use jQuery's .toggleClass()
for this. 你可以使用jQuery的
.toggleClass()
。
For example, if you have this form: 例如,如果您有此表单:
<form id="myForm">
<input type="text" id="myInput" class="visible clickable" />
<div id="myDiv" class="hidden clickable">Hello</div>
</form>
and .visible
and .hidden
definitions are: 和
.visible
和.hidden
定义是:
.visible {
display: inline;
}
.hidden {
display:none;
}
then your javascript should be: 那你的javascript应该是:
$('.clickable').click(function() {
$('#myForm .clickable').toggleClass('visible').toggleClass('hidden');
});
Here's a working jsFiddle: http://jsfiddle.net/A4Lvu/ 这是一个有用的jsFiddle: http : //jsfiddle.net/A4Lvu/
You could store the existing elements and reload them like this: 您可以存储现有元素并重新加载它们,如下所示:
$(document).ready(function () {
var collection = {};
$('#btnChange').click(function () {
$('#products, #mrp, #discount').each(function () {
if (this.nodeName.toLowerCase() === 'input') {
collection[this.id] = this;
$(this).replaceWith('<div id="' + this.id + '">' + this.value + "</div>");
} else {
$(this).replaceWith(collection[this.id]);
}
});
});
});
A fiddle is here . 这里有一个小提琴 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.