简体   繁体   English

从列表jquery中获取最接近的值

[英]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 . 我需要从我的列表中获取最接近的类html,但如果我直接放置closest ,它总是返回null。 i try some other thinks, but its not working. 我尝试了其他一些想法,但它不起作用。

the html: 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 ). 所以,如果我悬停在最后一个LI(对于exp。),悬停将获得最接近的类effectLeg并给我HTML或其他内容(在这种情况下为STUFFS 2)。

the js : 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 最近我得到使用发现,但发现只有得到我的第一个值li

i made a exp: check the Demo 我做了一个exp:检查演示

.closest() searches the an element's ancestors, but it looks like you're trying to search the siblings. .closest()搜索元素的祖先,但看起来你正试图搜索兄弟姐妹。 I think you just want .prev() : 我想你只想要.prev()

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

Demo: http://jsfiddle.net/mattball/nggyX/ 演示: 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 这将返回#ulId的html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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