这是我的第一部分代码:
$('ul li').click(function(){ //when an <li> is clicked
$('ul .clicked').removeClass('clicked'); // remove .clicked class from any other <li>'s inside a <ul>
$(this).addClass('clicked'); // add .clicked class to the clicked <li> ($(this))
screen = $(this).attr('id'); // screen = the clicked elements' id
screen = "#" + screen; // screen = the clicked elements' id with a # infront of it
$(screen).screenSlide(); // is basically = $('#elementsID').screenSlide();, correct?
});
这很奇怪,因为在我之前写的一个函数中,除了最后一步,我做了完全相同的事情,而不是将 screen 作为选择器传递,我将 screen 插入一个数组,然后我抓取数组 [0](这是#elementsID 没有任何引号)并将其用作选择器并且它起作用了。但是向前看,screenSlide 是
function screenSlide(){ // $(this) should = an <li> who's id is screen
var test = $(this).attr('class');
alert(test);
$(this).addClass('current'); // add the .current class to $(this), which should be an <li>
$(this).slideDown();
};
现在,警报测试没有发出任何警报,所以我猜测将屏幕作为 CSS 选择器传递是行不通的。可以看到,screenSlide 函数应该是给 $(this)
知道哪里出了问题吗?
最佳答案
按照您定义的方式,screenSlide
只是一个函数,没有附加到 jquery 对象。为了在 jquery 对象上作为函数调用,您需要将其添加为 $.fn.screenSlide
。
$.fn.screenSlide = function(){
var test =this.attr('class');
alert(test);
this.addClass('current'); // add the .current class to $(this), which should be an <li>
this.slideDown();
return this; //return this to enable chaining
}
在这个函数中,您不需要将 jquery 对象重新定义为 $(this),因为 this 已经是一个 jquery 对象,并且还返回 this
以启用它以进行链接。
如果你想单独调用它,那么你可以使用 function.call
screenSlide.call($(this));
有了这个 this
又是一个 jquery 对象,你不需要在你的函数中再次执行 $(this)
。
顺便说一下,您似乎只需要将它作为 $(this).screenSlide();
调用,除非您复制 id,在这种情况下它不会运行反正你期望的方式。
关于javascript - 将变量作为 JQuery CSS 选择器传递不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19286029/