2013-04-26 35 views
0

那么我有3个按钮,这些必须只有一个类.fdm所以每个按钮如何可能有不同的操作,只是调用类?如何为每个3个不同的按钮使用不同的动作?

我实际上使用,但像这样我必须设置ID到每个按钮。我不想要这个,我想设置一个类名并为所有按钮标识差异行为。

JS:

jQuery(function(){ 
$('#r').bind('click',function(){ 
$('#alvo').css('background','#ff0000'); 
}) 
$('#g').bind('click',function(){ 
$('#alvo').css('background','#155c00'); 
}) 
$('#b').bind('click',function(){ 
$('#alvo').css('background','#001eff'); 
}) 
}) 

HTM:

<div id="alvo" style="width:200px;height:200px;border:2px #000 solid;"> 
</div> 

<button class="fdm" type="button" id="r">R</button> 
<button class="fdm" type="button" id="g">G</button> 
<button class="fdm" type="button" id="b">B</button> 

就像我说的,我只是想用一个类名来这里更新了小提琴的所有按钮

Fiddle

+0

什么是不使用'id'来做到这一点的原因?为什么你想让你的按钮只有一个'class'? – 2013-04-26 11:05:24

+0

这和家庭作业形成高中,按钮的差异操作havin相同的类没有身份证。 – guihknx 2013-04-26 11:06:46

回答

3

http://jsfiddle.net/EGn9z/2/

$(function(){ 

    $ (".fdm").click(function(){ 
     $('#alvo').css('background', $(this).attr("data-color")); 
    }); 

}) 

<div id="alvo" style="width:200px;height:200px;border:2px #000 solid;"> 
</div> 

<button class="fdm" type="button" id="r" data-color="#ff0000">R</button> 
<button class="fdm" type="button" id="g" data-color="#00ff00">G</button> 
<button class="fdm" type="button" id="b" data-color="#0000ff">B</button> 

已经把颜色数据属性

+0

击败了我 - 这也是我的方式! – Pete 2013-04-26 11:07:44

+0

只是完美的我想要的,很多thx。 – guihknx 2013-04-26 11:09:39

+2

** FYI:**'$(this).attr(“data-color”)'=='$(this).data(“color”)' – George 2013-04-26 11:11:39

1

正如你不能添加其他类和不能使用id,你可以决定如何使用按钮的text行动:

$(function(){ 
    $('.fdm').bind('click',function(){ 
    var text = $(this).text(); 
    if(text == 'R') 
     $('#alvo').css('background','#ff0000'); 
    if(text == 'G') 
     $('#alvo').css('background','#155c00'); 
    if(text == 'B') 
     $('#alvo').css('background','#001eff'); 
    }) ;  

}); 
+0

太棒了!我怎么能注意到有很多方法可以做到这一点,thx。 – guihknx 2013-04-26 11:19:59

相关问题