如何从这个jQuery函数返回克隆的元素?

How can I return the cloned element from this jQuery function

本文关键字:元素 返回 函数 jQuery      更新时间:2023-09-26

我有:

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)的数组,但没有工作。

这就行了:

$.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/