使用jQuery在父容器中查找元素 [英] Find element within parent container with jQuery
本文介绍了使用jQuery在父容器中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是在遇到麻烦时才尝试将我的LI中的元素作为目标,我已经阅读了jQuery文档,但无法弄清楚我在做什么错?
Im trying to target an element within my LI only im having trouble, I've read the jQuery documentation but cant figure out what im doing wrong?
在单击事件中,我想找到一个元素并更改其中的html ...
On a click event I want to find an element and alter the html inside...
<li>
<h2>400</h2>
<form>
<input type='submit' class='click' value='send'>
</form>
</li>
$('.click').click(function(){
$(this).parent('li').closest('h4').html('asdasd');
});
推荐答案
基于以下HTML(请记住,我必须用ul
包装li
,因为展开的li
是无效的HTML) :
Based on the following HTML (bear in mind I had to wrap the li
with the ul
, since an unwrapped li
is invalid HTML):
<ul>
<li>
<h2>400</h2>
<form>
<input type='submit' class='click' value='send'>
</form>
</li>
</ul>
以及以下jQuery:
And the following jQuery:
$('.click').click(function(){
$(this).parent('li').closest('h4').html('asdasd');
});
似乎您正在尝试在li
中找到h4
.您遇到的问题是多种的:
It seems you're trying to find the h4
within the li
. The problems you're having are multiple:
- 使用
parent()
仅查找当前元素的直接父元素;而是使用closest()
来查找祖先直到,找到匹配的元素 -
closest()
(如前所述)通过祖先元素看起来是 up ,而您试图在li
元素的后代中找到一个元素.使用find()
, - 您正在搜索不存在的
h4
元素.您需要(我想)才能找到DOM中存在的h2
.
- Using
parent()
only looks up to the immediate parent element of the current element; useclosest()
instead, to look up through the ancestors until it finds a matching element, closest()
(as mentioned) looks up through the ancestor elements, while you're trying to find an element among the descendants of theli
element. Usefind()
,- You were searching for an
h4
element, which didn't exist. You needed (I assume) to find theh2
that was present in the DOM.
所以:
$('.click').click(function(){
$(this).closest('li').find('h2').html('asdasd');
});
参考文献:
这篇关于使用jQuery在父容器中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文