我有一个管理子菜单的jQuery脚本。当用户单击div时,div将更改为活动状态,然后内容会相应地更改颜色。这些按钮的id标签与相应的div标签相同,并添加了“_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?
})
答案 0 :(得分:1)
这应该适合你:
var current_id = $(this).attr('id');
var other_id = current_id + '_button';
$('#' + other_id).css('color', 'red');
答案 1 :(得分:0)
您只需添加$('#' + yourid)
$('#' + this.id.replace('_button', '')).css('color', 'red');