javascript - 如何使用 jQuery 将输入替换为保留所有属性的文本区域?

标签 javascript jquery dom attributes properties

我有一个文本输入,我想将其替换为文本区域,同时保留所有属性。我如何使用 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));
});​

示例:http://jsfiddle.net/FyYDT/

已添加

如果你想让 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));

});​

http://jsfiddle.net/FyYDT/1/

关于javascript - 如何使用 jQuery 将输入替换为保留所有属性的文本区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9549804/

相关文章:

javascript - 如何使用 Ajax 发送 header

javascript - 如何使用 CSS3 过渡

javascript - jQuery 的 $.引用?

javascript - casperJS assertExists 不传递带有空格的类

javascript - 在 jquery ajax 中访问变量

javascript - 通过 jQuery 从 ASP.NET 中的 Web 服务获取数据

javascript - 使用文件中的内容加载文本区域

jquery - 使用 EmberJS 调用 jQuery 插件会创建竞争条件

javascript - 仅向首次查看者显示消息

javascript - 如何在 ember.js 中重用/干燥这些路由