如果您需要这种类型的功能, 请更新当前的解决方案https://gist.github.com/jdaly13/5581538#file-gistfile1-js
我正在尝试一个小实验,我试图用我自己的方法覆盖 jQuery 的核心 end 方法,该方法实际上只是为其添加了功能
例如,如果你正在使用 jQuery,你可能会做这样的事情
$('h1.clickme').click(function () {
$(this).next('div').css("width", "+=200").parent().next().hide().end().end()
//this should traverse you back to the div after the h1 clicked
})
例如,我想通过添加添加数字参数的功能来覆盖 jQuery end 方法
.end(1)
会做同样的事情
.end().end()
这是我到目前为止所拥有的
(function(){
// Define overriding method.
jQuery.fn.end = function(no_of_times){
var prevObject = "prevObject";
if (!(arguments.length) || (typeof no_of_times !== "number")) {
return this.prevObject || this.constructor(null);
} else {
if (no_of_times == 1) {
return this.prevObject.prevObject || this.constructor(null)
} else if (no_of_times == 2) {
return this.prevObject.prevObject.prevObject || this.constructor(null)
} else if (no_of_times == 3) {
return this.prevObject.prevObject.prevObject.prevObject || this.constructor(null)
} else {
//too many times can't type anymore
return this.prevObject || this.constructor(null);
}
}
}
})()
所以我可以这样称呼
$('.promo-carousel').parent().prev().siblings('span').hide().end(2)
但显然我不认为写出所有这些 if 语句是有效的。有没有更简单的方法来做到这一点?我确定性能大致相同,但为了便于阅读,我正在这样做
我想根据传递的参数在 prevObject 变量中附加“prevObject”字符串
if (!(arguments.length) || (typeof no_of_times !== "number")) {
return this.prevObject || this.constructor(null);
} else {
for (i=0; i <= no_of_times; i++) {
pObj += "prevObject."
}
var prevObject = pObj.slice(0, prevObject.length -1)
console.log(prevObject);
return this.prevObject
}
}
但是上面的那段代码不起作用任何帮助一如既往地受到赞赏