我有一个文本输入,我想将其替换为文本区域,同时保留所有属性。我如何使用 jQuery 做到这一点?
示例输入:
<input type="text" name="newfeature" id="newfeature"
class="form-required" tabindex="3"
aria-required="true" />
期望的输出:
<textarea type="text" name="newfeature" id="newfeature"
class="form-required" tabindex="3"
aria-required="true"></textarea>
我知道这可以使用 .prop()
选择器手动完成并指定每个属性/属性,但我如何才能动态地完成它?
此外,这不是必需的,但是这样做时是否可以保留绑定(bind)?
最佳答案
这也适用于 value
属性:
$('input').each(function() {
var attrs = {};
$.each(this.attributes, function() {
attrs[this.name] = this.value;
});
$(this).replaceWith($('<textarea>').prop(attrs));
});
已添加
如果你想让 jQuery 事件一起传递(不推荐),你需要重新绑定(bind)它们。像这样的东西:
$('input').click(function() {
alert('hey');
}).each(function() {
var attrs = {},
ta = $('<textarea>');
$.each(this.attributes, function() {
attrs[this.name] = this.value;
});
$.each($(this).data('events'), function(i, f) {
$.each(f, function(){
ta.bind(i, this.handler);
});
});
$(this).replaceWith(ta.prop(attrs));
});
关于javascript - 如何使用 jQuery 将输入替换为保留所有属性的文本区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9549804/