2012-08-10 50 views
0

目前進行簡單的幻燈片可重複使用的...創建我使用這個函數的JavaScript函數

function jeans(jean, links) { 

$(links).hide(); 

$(jean).hover(

    function() { 
     $(links).show('slow'); 
    }, 

    function() { 
     $(links).hide('slow'); 
});} 

,把它與地方需要...

jeans('#red-jeans', '#red-jeans ul'); 
jeans('#blue-jeans', '#blue-jeans ul'); 
jeans('#yellow-jeans', '#yellow-jeans ul'); 

我'喜歡能夠通過在父母「#red-jeans」上附加一個班級來完成此任務。

我特林像

function jeans(selector) { 

$(selector 'ul').hide(); 

$(selector).hover(

    function() { 
     $(selector 'ul').show('slow'); 
    }, 

    function() { 
     $(selector 'ul').hide('slow'); 
});} 

...但我的語法是殘酷的!

如果有人能指引我正確的方向,將非常感謝!


現在的問題是,幻燈片在每個我上課的元素上運行。任何人都可以推薦一個修改,只會激活當前的懸停?我認爲(此)需要某處...

謝謝!

回答

1

有幾種方法,你可以在一個乾淨的方式實現這一目標:

$(selector).find('ul') 
$(selector + ' ul') 
$('ul', selector) 

都是等價的。

一般來說,我建議你緩存選擇器,如果你更頻繁地使用它們,因爲在內部調用$()可能會非常昂貴。通過這種方式,您可以在重構時獲得更好的性能和更少的麻煩。
要使幻燈片取決於您當前的懸停,請使用$(this)代替常規selector

function(selector){ 

    var $element = $('ul', selector); 

    $element.hide(); 

    $(selector).hover(
    function() { 
     $(this).find('ul').show('slow'); 
     }, 
    function() { 
     $(this).find('ul').hide('slow'); 
    }); 

} 
+0

完美,謝謝! – Cordial 2012-08-10 10:47:33

3

此:

$(selector 'ul').hide(); 

應該

$('ul', selector).hide(); 

以及所有其他類似的地方。這裏做的事情就是找ul元素中selector

+0

那太好了,謝謝!現在的問題是幻燈片在我上課的每個元素上運行。你知道我會怎麼去只在當前懸停時激活它嗎? – Cordial 2012-08-10 10:10:59

+0

@Cordial看看我的答案,這可能是解決方案。 – Christoph 2012-08-10 10:23:16

+0

@Cordial - 我第二個什麼christoph說 - 他看起來像解決方案 – Jamiec 2012-08-10 10:24:21

0

您只需將字符串: $(selector + ' ul').hide('slow');

0

你可以嘗試更新您的JavaScript function如下:

function jeans(selector) { 

    // you will have to use 'find' and it wil only be for the first 'ul' as well 
    $(selector).find('ul:first').hide(); 

    $(selector).hover(

    function() { 
     $(selector).find('ul:first').show('slow'); 
    }, 

    function() { 
     $(selector).find('ul:first').hide('slow'); 
    }); 
} 

然後調用它像這樣...我想這將有助於

1

已經回答,但這是做同樣事情的好方法。你可以像這樣創建自己的jQuery插件...

$.fn.jeans = function() { 
    $(this).find("ul").hide(); 
    $(this).hover(
     function() { 
      $(this).find("ul").show('slow'); 
     }, 
     function() { 
      $(this).find("ul").hide('slow'); 
     } 
    ); 
} 

您選擇的元素將其應用到和使用它像一個普通的jQuery函數調用它...

$("#red-jeans, #blue-jeans, #yellow-jeans").jeans(); 

只是備查;)

相關問題