简体   繁体   中英

get the closest value from a list jquery

i need to get the closest class html from my list, but its always returning null if i put directly the closest . i try some other thinks, but its not working.

the html:

<ul id="ulId">
  <li class='effectLeg'>
    Stuffs
  </li>
  <li class='test legColor' style=''></li>
  <li class='effectLeg'>
    Stuffs 2
  </li>
  <li class='test legColor'></li>
</ul>

so, if i hover the last LI (for exp.) the hover will get the closest class effectLeg and give me the HTML or anything inside ( in that case the STUFFS 2 ).

the js :

$(".legColor").live("hover", function(){
    alert($(this).closest("#ulId").find(".effectLeg").html());
});

the closest i get was using find, but the find only get the first value of my li

i made a exp: check the Demo

.closest() searches the an element's ancestors, but it looks like you're trying to search the siblings. I think you just want .prev() :

$(".legColor").live("hover", function(){
    console.log($(this).prev('li.effectLeg'));
});

Demo: http://jsfiddle.net/mattball/nggyX/

Your syntax is incorrect ... Depending on what closest thing you are after you'd be doing:

alert($(this).closest("ul").html()); 

That would return the html of #ulId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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