使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:09:01  来源:igfitidea点击:

Find element within parent container with jQuery

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...

http://jsfiddle.net/68ePW/3/

http://jsfiddle.net/68ePW/3/

<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 liwith the ul, since an unwrapped liis invalid HTML):

基于以下的HTML(请记住,我不得不换行liul,因为展开的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 h4within the li. The problems you're having are multiple:

看来您正试图h4li. 您遇到的问题是多方面的:

  1. Using parent()only looks up to the immediate parent element of the current element; use closest()instead, to look up through the ancestors untilit finds a matching element,
  2. closest()(as mentioned) looks upthrough the ancestor elements, while you're trying to find an element among the descendants of the lielement. Use find(),
  3. You were searching for an h4element, which didn't exist. You needed (I assume) to find the h2that was present in the DOM.
  1. 使用parent()只查找当前元素的直接父元素;closest()改为使用,在祖先中查找,直到找到匹配的元素,
  2. closest()(如前所述)查找通过祖先元素,而你试图找到的后代中有一个元素li的元素。使用find(),
  3. 您正在搜索一个h4不存在的元素。您需要(我假设)找到h2存在于 DOM 中的 。

So:

所以:

$('.click').click(function(){
    $(this).closest('li').find('h2').html('asdasd');
});

JS Fiddle demo.

JS小提琴演示

References:

参考: