如何使用jquery

时间:2016-07-13 11:06:27

标签: javascript jquery html html-lists

<li id="menu-item-52" class="menu-item menu-item-type-post_type menu-item-object-page current-page-ancestor current-menu-ancestor current-menu-parent current-page-parent current_page_parent current_page_ancestor menu-item-has-children menu-item-52"><a href="https://fxem.com/trading-accounts/">Trading Accounts</a>
        <ul class="sub-menu">
            <li id="menu-item-55" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-55"><a href="https://fxem.com/trading-accounts/demo-account/">Get DEMO Account</a></li>
            <li id="menu-item-54" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-44 current_page_item menu-item-54"><a href="https://fxem.com/trading-accounts/live-account/">Get LIVE Account</a></li>
            <li id="menu-item-53" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-53"><a href="https://fxem.com/trading-accounts/deposit-and-withdrawal/">Deposit and Withdrawal</a></li>
        </ul>
    </li>

<script>
   $('.menu-item ul.sub-menu li').click(function(){
        var main_id = $(this).attr('id');
    });
</script>

我希望获得此ID&#39; menu-item-52&#39;点击menu-item-55

3 个答案:

答案 0 :(得分:0)

$('#menu-item-55').click(function() {
  var id = $(this).closest('li').attr('id')
  console.log(id)


})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="menu-item-52" class="menu-item menu-item-type-post_type menu-item-object-page current-page-ancestor current-menu-ancestor current-menu-parent current-page-parent current_page_parent current_page_ancestor menu-item-has-children menu-item-52"><a href="https://fxem.com/trading-accounts/">Trading Accounts</a>
  <ul class="sub-menu">
    <li id="menu-item-55" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-55"><a href="https://fxem.com/trading-accounts/demo-account/">Get DEMO Account</a>
    </li>
    <li id="menu-item-54" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-44 current_page_item menu-item-54"><a href="https://fxem.com/trading-accounts/live-account/">Get LIVE Account</a>
    </li>
    <li id="menu-item-53" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-53"><a href="https://fxem.com/trading-accounts/deposit-and-withdrawal/">Deposit and Withdrawal</a>
    </li>
  </ul>
</li>

使用closest(),然后添加li以获取父

答案 1 :(得分:0)

使用此:

&#13;
&#13;
 apt-get install php5-intl
&#13;
$('.menu-item ul.sub-menu li').click(function(){
     var main_id = $(this).parent('ul').closest("li").attr("id");
     alert(main_id)
});
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我通过使用以下jQuery代码完成了这个:

$("#menu-item-55").closest('ul').parent().attr('id');

查看小提琴链接:Click here

希望它可以帮助你:)