简体   繁体   English

通过jquery将值设置为click事件元素的ID

[英]Set the value to ID of the element on click event by jquery

I want to set the menu to active when click on it. 我想在单击菜单时将其设置为活动菜单。 This is what I've tried : 这是我尝试过的:

<script language="javascript" type="text/javascript">
  var select;
  $(document).ready(function () {
    $.getJSON(url, function (data) {
     $.each(data, function (index, dataOption) {

      var new_li = $("<li class='level1' id='select_list'><a href='javascript:void(0);' id='" + dataOption.ID + "' class ='selectedcategory'>"  + dataOption.Name + "</a>");

      $('a#' + dataOption.ID).click(function () {
        select = "selected";
        $('.level1').attr("id",select);
      });
     });
    });
  });
</script>

What I tried to do is to set the id of 'level1' to selected, when I click on that link. 当我单击该链接时,我想做的是将“ level1”的ID设置为selected。 But my coding is set all the link to selected, even I click only 1 link. 但是我的编码将所有链接都设置为选中,即使我仅单击1个链接。

Could anyone give me the solution please. 任何人都可以给我解决方案。

Thanks so much. 非常感谢。

That happens because you are calling .attr() on all .level1 element instead of only the one being clicked by its child so, 发生这种情况是因为您正在所有.level1元素上调用.attr() ,而不是仅其子元素单击该元素,因此,

change 更改

$('.level1').attr("id",select);

to

$(this).parent().attr('id', select);

You also need to remove the "selected" id from the other <li> 's by 您还需要删除其他<li>的“选定” ID

$('.level1').removeAttr('id');

So the complete code looks like: 因此,完整的代码如下所示:

  $('a#' + dataOption.ID).click(function () {
      $('.level1').removeAttr('id');
      $(this).parent().attr("id", 'selected');
  });

One suggestion though, class is usually used in situation like this when you want to have a selected type of a list of menu, if you are using class you'd do something like 但是,有一个建议,当您要selected菜单列表的selected类型时,通常在这种情况下使用类,如果您正在使用类,则应执行以下操作

$('a#' + dataOption.ID).click(function () {
    $('.level1').removeClass('selected');
    $(this).parent().addClass('selected');
}

Looks more concise that way, but I'll leave it up to you :) 这样看起来更简洁,但我会留给您:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM