使用jQuery在父容器中查找元素 [英] Find element within parent container with jQuery

查看:273
本文介绍了使用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...

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');
});

推荐答案

基于以下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:

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

所以:

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

JS Fiddle演示.

参考文献:

这篇关于使用jQuery在父容器中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆