2009-08-20 85 views
1

我現在用的是下面這段jQuery代碼重用jQuery的準備代碼:傳遞參數

$('div#addMenu1').click(function(){ 
    if (!menuSet1){ 
     menuSet1 = true; 
        $('div#sliderOne').slideDown('slow'); 
        $('img', this).attr('src', 'Green_Up.png'); 
        $('img', this).attr('title', 'Collapse'); 
        $('div#sliderOne').css("background-color", "#cee8ff"); 
    } 
    else { 
     menuSet1 = false; 
        $('div#sliderOne').slideUp('slow'); 
        $('img', this).attr('src', 'Green_Down.png'); 
        $('img', this).attr('title', 'Create a top menu item'); 
    } 
}); 

的事情是,雖然,我想重用的代碼相同的位,但能也檢查DIV #addMenu [1234]以及設置menuSet [1234]並更改img標題

任何想法如何重用此代碼,但基於用戶點擊的div部分,傳遞節號,如3和新標題對於img,這個代碼,所以它會使用:

 $('div#addMenu3').click(function(){ 
    if (!menuSet1){ 
     menuSet3 = true; 
        $('div#sliderOne').slideDown('slow'); 
        $('img', this).attr('src', 'Green_Up.png'); 
        $('img', this).attr('title', 'Collapse'); 
        $('div#sliderOne').css("background-color", "#cee8ff"); 
    } 
    else { 
     menuSet3 = false; 
        $('div#sliderOne').slideUp('slow'); 
        $('img', this).attr('src', 'Green_Down.png'); 
        $('img', this).attr('title', 'Create a Level 3 menu item'); 
    } 
}); 

希望這是有道理的。

謝謝。 Tony。

回答

2

我不確定這是否涵蓋了您的問題的範圍,但jQuery UI提供了一個accordion control,它涵蓋了您似乎想要做的事情。

+0

謝謝你的 - 我會看看,但如果我可以以某種方式重用我有的代碼,我會先嚐試。 – tonyf 2009-08-20 05:51:26

0

您可以將數據傳遞到事件處理程序,如果你使用bind()的味道... http://docs.jquery.com/Events/bind

+0

謝謝斯科特 - 我會看看。希望我可以通過正確的信息。 – tonyf 2009-08-20 05:52:12

0

你可以掀起一個小插件。由於它是「空氣編碼」,因此可能存在問題。

$.fn.dropper = function(args) { 
// some default options - extended by args 
var opts = $.extend({ 
    sliderElem: null, 
    sliderBg: '#cee8ff', 
    imgOpen: 'Green_Up.png', 
    imgClosed: 'Green_Down.png', 
    titleOpen: 'Collapse', 
    titleClosed: 'Open', 
    openClass: 'open',  
}, args); 

this.click(function() { 
    // using a "hasClass" instead of your boolean logic 
    if ($(this).hasClass(opts.openClass)) { 
    $(this).removeClass(opts.openClass); 

    // the opts will be passed in when you call the plugin 
    $(opts.sliderElem).slideUp('slow'); 
    $('img', this).attr('src', opts.imgClosed).attr('title', opts.titleClosed); 
    } else { 
    $(this).addClass(opts.openClass); 

    $(opts.sliderElem).slideDown('slow').css('background-color', opts.sliderBg);   
    $('img', this).attr('src', opts.imgOpen).attr('title', opts.titleOpen); 
    } 
}); 
return this; 
} 


$('div#addMenu1').dropper({sliderElem: 'div#sliderOne'}); 
$('div#addMenu3').dropper({sliderElem: 'div#sliderThree', titleClosed: 'Create a Level 3 menu Item'});