-1

Sure this must've been asked here before but can't find anything.

I have a page with a list of buttons on the left, and a list of divs on the right. Each button has a class that corresponds to the ID of the div. So for example, button one is ".button1" and when clicked, does something to "#div1", ".button2" to "#div2" and so on. If this was my script:

$('.button1').click(function(){
    $("#div1").css("color","red");
});
$('.button2').click(function(){
    $("#div2").css("color","red");
});
and so on...

...ペアごとに繰り返すのではなく、クリックされたボタンのクラスを取得し、最後の番号を確認し、div ID を確認して、対応するボタンと一致させることができることを知っています。

しかし、私はそれについて行く方法がわかりません!

4

4 に答える 4

1

Ew、これはイベント委任を使用した最小限の作業例です。これはボタンが999個あってもお守りとして機能します。必要のないときに 999 個のイベント ハンドラーを追加して、悪用をやめるべきです。

http://jsfiddle.net/5YYDU/

$("#buttons").on("click",":button",function(e){
    $("#div"+$(this).attr("id").replace(/[^0-9]/g, '')).css("background","red");
});
于 2013-07-19T09:14:23.553 に答える
1

このようなものはどうですか?

jsFiddle の作業: http://jsfiddle.net/AWvv5/2/

クリック ハンドラーを btn クラス全体に割り当ててから、ハンドラー内の "btn" を "div" に置き換えるだけです。

HTML:

<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>

<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>

Javascript:

$(".btn").click(function(e){
    var divId = this.id.replace("btn","div");
    $("#"+divId).css("color","red");
});
于 2013-07-19T09:02:27.377 に答える