我想知道如何在jQuery
对象的原生原型函数中使用String
。
我试过了:
String.prototype.jQ = function() {
var $currentObject = $( this );
return ( $currentObject.length ) ? $currentObject.val() : this;
};
var test = "#txtEmail";
alert( test.jQ() );
没有运气。有什么建议吗?
我完全清楚我可以使用$( test ).val()
,但我想知道我是否可以按照自己的方式去做。
谢谢!
答案 0 :(得分:2)
奇怪的是,jQuery只接受原始字符串值作为选择器,而不是String对象,这是this
原型方法中的String
。您可以使用.valueOf()
来获取原语:
String.prototype.jQ = function() {
var $currentObject = $(this.valueOf());
return $currentObject.length ? $currentObject.val() : this;
};
答案 1 :(得分:1)
$(this +“”); //因为“this”目前是一个字符数组
String.prototype.jQ = function() {
var $currentObject = $( this + "");
return ( $currentObject.length ) ? $currentObject.val() : this;
};
var test = "#txtEmail";
alert( test.jQ() );