开发者

loop get parent html value if not first level

<ul>

<li>
    <a class="level" title="" href="">A</a>
    <ul>
        <li>
            <a class="level" title="" href="">AA</a>
            <ul>
            </ul>
        </li>
        <li>
            <a class="level" title="" href="">AB</a>
            <ul>
                <li>
                开发者_运维百科    <a class="level" title="" href="">ABA</a>
                    <ul>
                    </ul>
                </li>
            </ul>
        </li>
        <li>
            <a class="level" title="" href="">AC</a>
            <ul>
            </ul>
        </li>
    </ul>
</li>
<li>
    <a class="level" title="" href="">B</a>
    <ul>
        <li>
            <a class="level" title="" href="">BA</a>
            <ul>
                <li>
                    <a class="level" title="" href="">BAA</a>
                    <ul>
                        <li>
                            <a class="level" title="" href="">BAAA</a>
                            <ul>
                            </ul>
                        </li>
                        <li>
                            <a class="level" title="" href="">BAAB</a>
                            <ul>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
        <li>
            <a class="level" title="" href="">BB</a>
            <ul>
            </ul>
        </li>
        <li>
            <a class="level" title="" href="">BC</a>
            <ul>
            </ul>
        </li>
    </ul>
</li>

</ul>

how get html value of parent element with jquery when a.level click

AA click  result =  A/AA
AB click    "       A/AB

ABA click  result =  A/AB/ABA
AC click    "        A/AC

BA click  result =  B/BA
BAA click    "      B/BA/BAA

BAAB click   "      B/BA/BAA/BAAB

with infinite ul li level

$('a.level').click(function(){
  //
  return(false);
}

Thank you.


The element hierarchy in your markup makes it a little complicated, but you can walk up the <ul> ancestor chain with parents() and fetch the anchor elements you're interested in with prev().

From there, you can map() the text content of these elements and join() the resulting array into an absolute path:

$("a.level").click(function() {
    alert($(this).parents("ul").prev("a.level").add(this).map(function() {
        return $(this).text();
    }).get().join("/"));
});

You can see this solution in action in this fiddle.


$('a.level').click(function(){
  $(this).parents("a.level");
}


$('a.level').click(function(){
  var tempString = '';
  for(var i=0;i<$(this).parents('.level').length;i++){
      tempString += $(this).parents('.level').get(i).text + "/";
  }
  tempString += $(this).text;
  alert(tempString);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜