2012-12-07 18 views
0

我有一个管理子菜单的jQuery脚本。当用户点击div时,div变为活动状态,然后内容相应地改变颜色。按钮的id标签与相应的div标签相同,并添加了“_button”。例如,要更改颜色的div具有id标记'first',那么按钮id标记是'first_button'。以this.id作为输入并将输入的已更改ID输入到新函数中

我现在的代码对按钮来说工作正常,但我不确定如何正确插入编辑后的id标记以选择合适的div来使第二个jQuery调用变为红色。现在代码不会对div做任何事情,但我在控制台中也没有收到任何错误。我可以用一系列如果/然后的陈述来做到这一点,但这不够雅致。

$('.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? 
}) 

回答

1

这应该为你工作:

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

$('#' + other_id).css('color', 'red'); 
0

你只需要添加id选择是$('#' + yourid)

$('#' + this.id.replace('_button', '')).css('color', 'red'); 
相关问题