0

I am new to jQuery and i have a problem about getting the value that i need from a variable. More specific I have this list on html file.

<ul id="menu">
<li class="mainmenu" id="newsarticles"><a href="#">News &amp; articles</a>

    <ul id="newsarticles">
        <li class="submenu" id="news"> <a href="#">News</a>

        </li>
        <li class="submenu" id="articles"> <a href="#">Articles</a>

        </li>
    </ul>
    <li class="mainmenu" id="contactus"><a href="#">Contact Us</a>
    </li>
</ul>

Now i want to use the same function both to mainmenu and submenu.

$("#menu li").click(Menu_function);

My problem is that when i click on submenu, variable $(this) has two values. one for the li inside the submenu and one for the li of mainmenu.

now i would like to do something like this in my function:

var currentId = $(this).attr('id');

How could I get only one value?

Any help appreciated.

4

3 に答える 3

1

あなたが欲しいでしょう

$('#menu').click(function(evt) {
  var currentId = $(evt.target).closest('li').attr('id');
});
于 2013-03-01T19:35:02.723 に答える
1

「各」セレクターを使用して、両方のアイテムにクリック機能を追加できます。

$('#menu li').each( function(index) {
    $(this).click( function() {
      var id = $(this).attr('id');

      // do whatever you need to here
    });
});
于 2013-03-01T19:35:54.037 に答える
0

jqueryの各メソッドを使用して、それらすべてをトラバースし、それらにonclickを追加できます。dcpが彼の答えで述べたものに似た何か:

$('#menu li').each( function() {
    // add click method on this element ($(this))
    $(this).click( function() {
    });
});
于 2013-03-01T19:39:50.137 に答える