使用jQuery在父容器中查找元素
我试图在我的LI中定位一个元素只有我遇到麻烦,我已经阅读了jQuery文档,但无法弄清楚我做错了什么?
在点击事件上我想找到一个元素并改变里面的html …
http://jsfiddle.net/68ePW/3/
400
$('.click').click(function(){ $(this).parent('li').closest('h4').html('asdasd'); });
基于以下HTML(请记住,我必须用ul
包装li
,因为打开的li
是无效的HTML):
-
400
以下是jQuery:
$('.click').click(function(){ $(this).parent('li').closest('h4').html('asdasd'); });
看来你正试图找到里面的h4
。 你遇到的问题是多方面的:
- 使用
parent()
只查找当前元素的直接父元素; 使用closest()
来查找祖先, 直到找到匹配的元素, -
closest()
(如上所述)通过祖先元素查找,同时你试图在li
元素的后代中找到一个元素。 使用find()
, - 您正在搜索不存在的
h4
元素。 您需要(我假设)找到DOM中存在的h2
。
所以:
$('.click').click(function(){ $(this).closest('li').find('h2').html('asdasd'); });
JS小提琴演示 。
参考文献:
-
closest()
。 -
find()
。 -
parent()
。