使用 jQuery 在父容器中查找元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10325101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find element within parent container with jQuery
提问by Liam
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?
我试图在我的 LI 中定位一个元素,只是我遇到了问题,我已经阅读了 jQuery 文档,但无法弄清楚我做错了什么?
On a click event I want to find an element and alter the html inside...
在单击事件中,我想找到一个元素并更改里面的 html...
<li>
<h2>400</h2>
<form>
<input type='submit' class='click' value='send'>
</form>
</li>
$('.click').click(function(){
$(this).parent('li').closest('h4').html('asdasd');
});
回答by David says reinstate Monica
Based on the following HTML (bear in mind I had to wrap the li
with the ul
, since an unwrapped li
is invalid HTML):
基于以下的HTML(请记住,我不得不换行li
用ul
,因为展开的li
是无效的HTML):
<ul>
<li>
<h2>400</h2>
<form>
<input type='submit' class='click' value='send'>
</form>
</li>
</ul>??????????????????
And the following jQuery:
以及以下 jQuery:
$('.click').click(function(){
$(this).parent('li').closest('h4').html('asdasd');
});
It seems you're trying to find the h4
within the li
. The problems you're having are multiple:
看来您正试图h4
在li
. 您遇到的问题是多方面的:
- Using
parent()
only looks up to the immediate parent element of the current element; useclosest()
instead, to look up through the ancestors untilit finds a matching element, closest()
(as mentioned) looks upthrough 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.
- 使用
parent()
只查找当前元素的直接父元素;closest()
改为使用,在祖先中查找,直到找到匹配的元素, closest()
(如前所述)查找了通过祖先元素,而你试图找到的后代中有一个元素li
的元素。使用find()
,- 您正在搜索一个
h4
不存在的元素。您需要(我假设)找到h2
存在于 DOM 中的 。
So:
所以:
$('.click').click(function(){
$(this).closest('li').find('h2').html('asdasd');
});
References:
参考: