2012-09-15 83 views
3

请告诉我为什么div与编号AudioVol+..(ex.1,2,3 and other) 不要更改类名称,当点击类名称的元素option_audio_player_mute不能更改元素类别点击

也告诉我,我可以减少/重构我的代码?

$('.option_audio_player_mute').live('click', function() { 
    var idn = this.id.split('+')[1]; 
    var vol1 = $('#AudioVol1+' + idn); 
    if ($(this).hasClass('audio_mute')) { 
     vol1.removeClass('audio_vol_not_active').addClass('audio_vol_active'); 
    } else if ($(this).hasClass('audio_not_mute')) { 
     vol1.removeClass('audio_vol_active').addClass('audio_vol_not_active'); 
    } 
}); 

为什么不能正常工作?

+0

您还可以向我们展示HTML部分吗?顺便说一句''.live()''在'1.8.x'弃用,你需要使用'.on()' – balexandre

+1

尽量避免使用'+',使用'_'因为你不需要转义它们在写javascript时。 – balexandre

+0

也很好的缓存jquery对象'$(this)'在一个本地变量中,它可以提高复杂页面的性能 – Vivek

回答

1

+符号在CSS(和jQuery)选择器中有特殊含义:它用于指定adjacent sibling selectors

尝试用两个反斜杠逃离+登录您的ID选择:

var vol1 = $("#AudioVol1\\+" + idn); 
+0

谢谢你的帮助 –

1

你可以使用.toggleClass,并使用.on代替.live

$(document).on('click', '.option_audio_player_mute', function() { 
    var vol1 = $("#AudioVol1\\+" + this.id.split('+')[1]), 
     $this = $(this); 
    vol1.toggleClass('audio_vol_active', $this.hasClass('audio_mute')) 
     .toggleClass('audio_vol_not_active', $this.hasClass('audio_not_mute')); 
});