javascript 当子元素已知时如何在jQuery中获取父元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6205878/
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-10-25 19:50:39  来源:igfitidea点击:

How to get parent element in jQuery when child element is known?

javascriptjqueryhtmldomjquery-mobile

提问by Will Curran

I'm using jQuery Mobile which creates a lot of the DOM for you. I need to remove() radio buttons, but based on how the HTML is constructed in jQuery Mobile, I do not have an id for the parent div. I can easily grab both the input and labels, but need to also get rid of the our div to completely removed the entry styling from the list of radio buttons.

我正在使用 jQuery Mobile,它为您创建了很多 DOM。我需要 remove() 单选按钮,但根据 jQuery Mobile 中 HTML 的构造方式,我没有父 div 的 id。我可以轻松获取输入和标签,但还需要摆脱我们的 div 以从单选按钮列表中完全删除条目样式。

<div class="ui-radio">
  <input type="radio" value="ahBkMj" id="ahBkMj" name="spam" data-theme="c">
  <label for="ahBkMj" class="ui-btn ui-btn-icon-left ui-btn-up-c">
    <span class="ui-btn-inner">
      <span class="ui-btn-text">Foo</span>
      <span class="ui-icon ui-icon-ui-icon-radio-off ui-icon-radio-off"></span>
    </span>
  </label>
</div>

回答by tjm

Will jQuery's .parent()do ?

jQuery 会.parent()做吗?

回答by Frédéric Hamidi

Since the <div>element is the immediate parent of your <input>element, you can use the aptly-named parent()method:

由于<div>元素是元素的直接父<input>元素,您可以使用恰当命名的parent()方法:

$("#ahBkMj").parent().remove();

In the general case, if you want the first ancestor matching a selector, you can use closest():

在一般情况下,如果你想让第一个祖先匹配一个选择器,你可以使用closest()

$("#ahBkMj").closest("div").remove();

Note, however, that closest()includes the element itself in its search.

但是请注意,这closest()包括在其搜索中的元素本身。

回答by Bill Warren

this works for me.....

这对我有用.....

var child = '# or . and name of your child div... ';

var child = '# 或 . 和你孩子的名字 div... ';

var width = Math.round($(child).parent().width());