0

我有一个管理子菜单的 jQuery 脚本。当用户单击一个 div 时,该 div 变为活动状态,然后内容相应地改变颜色。这些按钮有一个与相应的 div 标签相同的 id 标签,并添加了“_button”。例如,要更改颜色的 div 具有 id 标签 'first',然后按钮 id 标签是 'first_button'。

我现在的代码适用于按钮,但我不确定如何正确插入编辑后的 ​​id 标记以选择适当的 div 以使用第二个 jQuery 调用变为红色。现在代码对 div 没有任何作用,但我也没有在控制台中收到任何错误。我可以用一系列 if/then 语句来做到这一点,但这很不优雅。

$('.port_menu_button').click(function() {
    $('.port_menu_button').removeClass('active');
    $(this).addClass('active');;
    $('.port_type').css('color', '#000');
    $($(this).attr('id').replace('_button', '')).css('color', 'red'); //this is the problem line. how do I take the id and put it in here?
})
4

2 回答 2

1

这应该适合你:

var current_id = $(this).attr('id');
var other_id = current_id + '_button';

$('#' + other_id).css('color', 'red');
于 2012-12-07T20:30:38.217 回答
0

您只需要添加 id 选择器即可$('#' + yourid)

$('#' + this.id.replace('_button', '')).css('color', 'red');
于 2012-12-07T20:24:15.700 回答