【问题标题】:How can I replace an input with a textarea preserving all attributes using jQuery?如何使用 jQuery 将输入替换为保留所有属性的文本区域?
【发布时间】:2012-03-03 20:55:53
【问题描述】:

我有一个文本输入,我想用文本区域替换它,保留所有属性。如何使用 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() 选择器并指定每个属性/属性手动完成,但我怎样才能动态完成呢?

另外,这不是必需的,但这样做时是否可以保留绑定?

【问题讨论】:

  • &lt;textarea&gt; 元素没有type 属性...
  • @ŠimeVidas .p​​rop() 负责处理。它还直接设置 value 属性。

标签: javascript jquery dom attributes properties


【解决方案1】:

这也适用于 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 事件传递(不推荐),您需要重新绑定它们。比如:

$('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/

【讨论】:

  • 也添加了事件克隆,虽然我个人更喜欢使用事件委托。
【解决方案2】:

我会简单地遍历inputs 属性:

function makeInputTextarea(inputElem) {
    var $textarea = $("<textarea></textarea>");
    $.each(inputElem.attributes, function(i, attrib){
        var name = attrib.name;
        var value = attrib.value;
        if(name === "type") return; // textareas don't have a "type" attribute
        $textarea.attr(name, value);
    });
    return $textarea;
}

【讨论】:

    【解决方案3】:
    $(function() {
        $('input[type="text"]').parent().each(function({
            $(this).html($(this).html().replace(/(<\/)input/gi, "$1textarea").replace(/(<textarea[^>]*)value\=['"](.*)['"]([^>]*)\/>/, "$1>$2</textarea>"));
        }));
    });
    

    应该这样做吗?

    你可以做一个

    $('input, textarea').live('click', function() {
        // do actions!
    });
    

    保留绑定

    【讨论】:

    • 对,但请记住,textarea 上没有内联 value="" 属性。因此,最好以某种方式循环遍历属性,使用.prop('attrName') 获取它们并使用.prop('attrName',value) 设置它们,而不是对其进行正则表达式。另外关于我想保留的绑定 - 这将是一个插件,所以我无法编辑原始绑定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多