如何使用jquery将类添加到div?

如何使用jquery将类添加到div?,jquery,menu,scroll,Jquery,Menu,Scroll,之前,我使用了一些jquery代码将css样式应用于选定的菜单项。这是我用于此的代码 <script type="text/javascript"> $(document).ready(function(){ $('#menu-sentient a').each(function(index) { if(this.href.trim() == window.location) $(this).addClass("selected"

之前,我使用了一些jquery代码将css样式应用于选定的菜单项。这是我用于此的代码

   <script type="text/javascript">
$(document).ready(function(){
    $('#menu-sentient a').each(function(index) {
        if(this.href.trim() == window.location)
            $(this).addClass("selected");
    });
});
</script>

但是现在我已经在一个页面中将菜单项链接到了一些ID。例如,链接到公文包ID的公文包菜单。所选类现在不工作。那么,如何使此代码在一个页面中对ID起作用呢?

您希望使所选菜单处于活动状态时可见

$(document).on('click','#menu-sentient a', function() {
      var tag = $(this).attr('href');
      $('#menu-sentient a').each(function(index, value) {
           if($(this).attr('href') === tag) {
                $(this).addClass('selected');
           }
      });
});

显示你的标记或fiddle。显示失败的代码和HTML。向我们展示有效的代码没有帮助:你是说当你点击菜单项时,你想让页面向下滚动到一个确定的页面片段吗?当我点击菜单项时,它向下滚动到相对id。但是所选的菜单css没有改变。例如,所选菜单项的样式为底部边框
$(document).on('click','#menu-sentient a', function() {
      var tag = $(this).attr('href');
      $('#menu-sentient a').each(function(index, value) {
           if($(this).attr('href') === tag) {
                $(this).addClass('selected');
           }
      });
});