2013-10-10 37 views
0

這裏是我的代碼的第一部分:傳遞變量在jQuery CSS選擇器不工作

$('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? 
}); 

這很奇怪,因爲在前面的功能,我寫的,我做了同樣的事情,除了最後一步,而不是作爲一個選擇器傳遞屏幕,我推動屏幕內的一個數組,然後我抓住數組[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)添加一個類,然後使其滑動。

有什麼想法嗎?

+0

你的意思是該警示框顯示了'undefined'呢,還是顯示不出來呢?另外,控制檯中是否有任何錯誤? –

+0

爲什麼不直接調用'screenSlide(this);'? –

+0

@SuperScript,當我這樣做時,警告框顯示未定義。 – user2817200

回答

2

自定義背景下您所定義的方式,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 
} 

在這個函數中你不需要redefind jQuery對象爲$(本),因爲這會已經是jQuery對象,並返回this啓用它的鏈接。

如果要單獨調用它,那麼你可以使用function.call

screenSlide.call($(this)); 

有了這個this又是你不需要做$(this)自己的函數中一遍jQuery對象。

順便說一句,你似乎只需要調用它作爲$(this).screenSlide();,除非你重複的ID,在這種情況下,它不會像你期望的那樣行事。

Demo

1

$(screen).screenSlide();會拋出一個錯誤,指出對象沒有screenSlide這樣的方法,因爲screenSlide不是與jQuery包裝器對象關聯的方法。你需要寫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(); 
} 

插件或調用screenSlide與像

screenSlide.call($(screen)) 
+0

嗯有趣。那麼如何讓screenSlide與JQuery包裝器對象關聯的方法? – user2817200

+1

@ user2817200如果你將它編寫爲上面給出的插件,它將與jQuery包裝器對象 –

+0

OH關聯,完美,謝謝。 – user2817200