jquery 中 closest和parent用法

来源:互联网 发布:linux tail 指定行 编辑:程序博客网 时间:2024/06/07 12:22

其实closest和parent方法在jquery中都是遍历的意思,就是从自身的dom开始进行不同方式的查找,parent是从自身查找元素最近父级元素,而closest是从自身查找临近元素。两者的含义不太相同,但有时表现的结果却有相似的地方。

<!DOCTYPE html><html><head><script type="text/javascript" src="/jquery/jquery.js"></script><style>  li { margin: 3px; padding: 3px; background: #EEEEEE; }  li.hilight { background: yellow; }</style></head><body>  <ul>    <li><b>Click me!</b></li>    <li>You can also <b>Click me!</b></li>  </ul><script>  $( document ).bind("click", function( e ) {    $( e.target ).closest("li").toggleClass("hilight");  });</script></body></html>

上面的例子中点击每个列表项,该列表项的背景会发生变化。如果将closest换成parent则只有点击到click me时候才会变化。

0 0