Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery-动态设置筛选器方法_Jquery_Variables_Methods_Parameters - Fatal编程技术网

jQuery-动态设置筛选器方法

jQuery-动态设置筛选器方法,jquery,variables,methods,parameters,Jquery,Variables,Methods,Parameters,我希望结合一些代码,但我不确定我想做的是可能的。基本上,我有一个包含一系列if/else语句的函数,在所有不同的情况下,有一行是相似的: $('#selector).prev('.class-selector').addClass('current'); $('#selector).next('.class-selector').addClass('current'); $('#selector).last('.class-selector').addClass('current'); $('#

我希望结合一些代码,但我不确定我想做的是可能的。基本上,我有一个包含一系列if/else语句的函数,在所有不同的情况下,有一行是相似的:

$('#selector).prev('.class-selector').addClass('current');
$('#selector).next('.class-selector').addClass('current');
$('#selector).last('.class-selector').addClass('current');
$('#selector).first('.class-selector').addClass('current');
有什么方法可以将筛选方法(
prev
next
last
first
)设置为变量,这样我就不必在整个函数中重复这一行了?我尝试将参数传递给函数并使用变量作为方法:

$('#selector).variable('.class-selector').addClass('current');
但这不起作用。我得到:

对象没有方法“变量”错误


根据jQuery代码的读取方式,我模糊地理解了为什么这不起作用。还有其他方法可以做到这一点吗?

这并不是很短,但肯定更简洁:)

var $all = $('#selector .class-selector')
$all.eq(0).addClass('current'); //first
$all.eq(4).addClass('current'); //fifth
$all.eq($all.length-1).addClass('current'); //last

您可以尝试将其作为jquery插件

(function( $ ){
    $.fn.pnlf = function(class_selector, current) {
        this.prev(class_selector).addClass(current);
        this.next(class_selector).addClass(current);
        this.last(class_selector).addClass(current);
        this.first(class_selector).addClass(current);

        return this;
    };
})( jQuery );

// Use the plugin on the selected element...
$("#selector").pnlf("class-selector", "current");

谢谢!这正是我要找的东西,我从这里就能找到它。它基本上就是我需要的[fn]语法。
(function( $ ){
    $.fn.pnlf = function(class_selector, current) {
        this.prev(class_selector).addClass(current);
        this.next(class_selector).addClass(current);
        this.last(class_selector).addClass(current);
        this.first(class_selector).addClass(current);

        return this;
    };
})( jQuery );

// Use the plugin on the selected element...
$("#selector").pnlf("class-selector", "current");