如何在原生String原型函数中使用jQuery

How can I use jQuery in a native String prototypal function?

本文关键字:jQuery 函数 原型 原生 String      更新时间:2023-09-26

我想知道如何在String对象的本机原型函数中使用jQuery

我试过:

String.prototype.jQ = function() {
    var $currentObject = $( this );
    return ( $currentObject.length ) ? $currentObject.val() : this;
};
var test = "#txtEmail";
alert( test.jQ() );

运气不好。有什么建议吗?

我很清楚我可以使用$( test ).val(),但我想知道我是否可以用我的方式。

谢谢!

奇怪的是,jQuery只接受基元字符串值作为选择器,而不接受string对象,这就是thisString原型方法中的作用。您可以使用.valueOf()来获取基元:
String.prototype.jQ = function() {
    var $currentObject = $(this.valueOf());
    return $currentObject.length ? $currentObject.val() : this;
};

这是一个演示。

$(this+");//因为"this"当前是一个字符数组

String.prototype.jQ = function() {
    var $currentObject = $( this + "");
    return ( $currentObject.length ) ? $currentObject.val() : this;
};
var test = "#txtEmail";
alert( test.jQ() );