开发者

Work with <ul> and <li> with Jquery

<li class="active">Menu1
    <ul id="first" value="">
        <li value="10">Whatever</li>
        <li value="15">Whatever</li>
        <li value="20">Whatever</li>
    </ul>
</li>
<li>Menu2
    <ul id="second" value="">
        <li value="30">Whatever</li>
        <li value="35">Whatever</li>
        <li value="40">Whatever</li>
    </ul>
</li>

Okay that's the HTML, so let me see now if I can describe the behavior I want.

Each <li> with a value is clickable. W开发者_JS百科hen that li is clicked, I want it to set the parent <ul>, that initially has a blank value, to whatever the value is of the <li> that was clicked. Basically try and mimic the behavior of a select box, because that's how the CSS is styling these elements anyway.


This should work:

$('li > ul > li').click(function(){
  $(this).parent().attr('value',$(this).attr('value'));
});

We set a click event on all internal li elements, then, when clicked, we set attribute "value" of a parent element with "value" of clicked element


$('ul > li').click(function() {
    $(this).parent().attr('value',$(this).attr('value'));
});


value is not a valid attribute of UL and has been deprecated from LI. With that said, here's how to handle click event for an LI and get the parent UL:

$('li').click(function() {
  var clickedLI = $(this);
  var parentUL = $(this).parent();
});


in handler:

$(this).parent().attr("value", $(this).attr("value"))


Try this:

$('ul > li[value]').click(function () {
    $(this).closest('ul').attr('value', this.value);
});

http://jsfiddle.net/mDmsW/3/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜