如何从此jQuery函数返回克隆元素

时间:2011-12-17 02:14:38

标签: javascript jquery plugins

这就是我所拥有的:

jQuery.fn.convertInputType = function(t){
  var e = this;
  e.each(function(i){
    var o = jQuery(this)
    ,   c = o.clone();
    c.attr('type',t);
    o.replaceWith(c);
  });
  return e;
}

我无法弄清楚要返回什么链接,如:

$('.example').convertInputType('password').css('background','blue');

我以为我可以构建一个像newReturnObj[i] = o.replaceWith(c)newReturnObj[i] = cnewReturnObj[i] = jQuery(c)这样的数组,但都不起作用。

1 个答案:

答案 0 :(得分:2)

这里有效:

$.fn.convertInputType = function ( type ) {  

    // we use .map() because we're replacing the set of elements  
    return this.map( function ( i, elem ) {
        var clone = $( this ).clone().attr( 'type', type );        
        $( this ).replaceWith( clone );        
        return clone[0];
    });  

};

现场演示: http://jsfiddle.net/qTqQr/1/