jQuery:获取元素的父代 [英] jQuery: getting parent of an element

查看:46
本文介绍了jQuery:获取元素的父代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的HTML:

<div class="votingButton">
       <i class="icon-chevron-up"></i>
</div>

您可以看到 i 元素的父元素是 div ,但是当我尝试通过jQuery获取 i 的父元素时,它会给我 i :

As you can see parent of i element is div, but when I try to get parent of i via jQuery it gives me i:

$(function () {
     $('.icon-chevron-up').on('click', function () {
        alert($(this).parent().html());
     });
 });

上面的代码给了我< i class ="icon-chevron-up"></i> ,我也尝试了以下情况:

Above code gives me <i class="icon-chevron-up"></i>, I also tried these cases:

$(this).closest('.votingButton').html()
$(this).parents().html()
$(this).parents('.votingButton').html()

但仍然得到< i class ="icon-chevron-up"></i>
有什么主意吗?

But still get <i class="icon-chevron-up"></i>
Any idea?

推荐答案

当然可以.您正在使用 .parent().html(). .icon-chevron-up 元素的父级的HTML是:

Of course it does. You're using .parent().html(). The HTML of the parent of your .icon-chevron-up element is:

<i class="icon-chevron-up"></i>

如果您将HTML修改为:

If you modified your HTML to:

<div class="votingButton">
    <i class="icon-chevron-up"></i>
    <span>Hello, world!</span>
</div>

$(this).parent().html()的结果将是:

<i class="icon-chevron-up"></i>
<span>Hello, world!</span>

这篇关于jQuery:获取元素的父代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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