2009-07-10 6 views
1

本当に迅速なjQueryの質問...途方もなくシンプルなjQueryの再利用可能な機能の質問

私はこの機能を持っている:

$(document).ready(function() { 

    $('a#show1').click(function() { 
    $('.item1').toggle(1000); 
    return false; 
    }); 

    $('a#show2').click(function() { 
    $('.item2').toggle(1000); 
    return false; 
    }); 

    // And it goes on... 
}); 

ページのスクリプトが稼動するすべてのユニークな、showitemのdivの任意の数を持っており、 itemX

show1show2の繰り返し機能と同じ機能をどのように書き換えることができますか。実質的に次のようになります。

$('a#showX').click(function() { 
    $('.itemX').toggle(1000); 
    return false; 
}); 

答えて

2
$("a[id^=show]").click(function(){ 
var id = $(this).attr("id"); 
var num = id.substring(4); 
$(".item" + num).toggle(1000); 
}); 

私はそれをテストしていない、それが動作願っています。

+0

ああ、あなたの場合のIDは ".itemshow1"になりますが –

+0

これを行う必要があります:$( "。item" + $(this).attr( "id"))。toggle (1000)。 – Keith

+0

@d、Keith:あなたは正しく、修正されました;) – usoban

0

あなたがどれだけ持っているか知っていれば、forループを使用して変数を追加することができます。


for(var i=1;i<=whatever;i++) 
{ 
    $('a#show' + i).click(function() { // ... etc ... // }); 
} 
0

これはアイデアです:

$('a#show1', 'a#show2').click(function() { 
    id = ".item" + this.id.substr(4); 
    $(id).toggle(1000); 
    return false; 
}); 
0
$('a[id^=show]').click(function() { 
    var id = $(this).attr('id'); 
    id = id.substring(id.length-1); 
    $('.item'+id).toggle(1000); 
    return false; 
}); 
+1

ニースのアプローチですが、数値が9を超えるときに壊れます。 – karim79

+1

部分文字列(4)または部分文字列( "show" .length)は分割されません – kgiannakakis

1

私は通常、DOMで一貫して相対的な位置にアイテムを保持しよう:

<a href="#" class="format-link show-extra">text</a> 
<div class="info-panel show-extra-panel">extra toggle text</div> 
1

@usobanは正しいアプローチがあります。これは、この作品のようなものになるだろう

//all <a> with class .show-extra 
$('a.show-extra').click(function() { 
    //get the next element with the class .show-extra-panel 
    $(this).next('.show-extra-panel').toggle(1000); 
    return false; 
}); 

- 最初のセレクタの 'starts with'構文は、表示されているアイテムの数に関係なく、すべての 'show'アイテムを検索します。コードを調整して、すべてのコードを使用するのではなく、 'id'の数値部分だけを抽出するか、 '.item1'の代わりに '.itemshow1'というクラスの要素を探します。

$("a[id^=show]").click(function(){ 
    $(".item" + this.attr("id").substr(4)).toggle(1000); 
}); 

EDIT @Keithも良いアプローチを持っている - 識別子の数値部分を必要としないように - - 「ショー」の要素をマークするためにクラスを使用し、次いで 'の相対位置に依存しますそれを見つけるために 'item'を押します。

関連する問題