【问题标题】:Getting parent <td> width from child's class name从孩子的班级名称获取父 <td> 宽度
【发布时间】:2012-12-30 04:02:57
【问题描述】:

有没有办法使用子元素的类名来获取元素的宽度?

 <td width='100%' nowrap='1' style='padding-left:2px; margin:2px;'>
     <font class='DialogHeaderTitleFont'>RudimentalDrumming.com Jackets</font>
 </td>

在上面的代码中,我想通过元素的类名“.DialogHeaderTitleFont”来获取元素的宽度,可以吗?

谢谢。

【问题讨论】:

  • 字体标签不再常用。使用 SPAN。

标签: jquery html


【解决方案1】:

您可以使用.width 函数来获取元素的宽度。

$('.DialogHeaderTitleFont').parent().width();

jQuery 提供width 函数的不同变体,例如innerWidthwidthouterWidth.. 更多详细信息请查看Find out what the width of an image is using jQuery

已编辑:错过了您想要父元素的宽度。谢谢@Kevin

【讨论】:

  • “使用 child 元素的类名” 可能需要在其中添加.closest.parent。字体标签通常也没有宽度。
  • @Vega。我和 KevinB 在一起。您应该使用 .closest 来适应未来的变化,尤其是考虑到 OP 使用遗留元素。很快就会被&lt;strong&gt; 包裹起来:)
【解决方案2】:

是的,只需使用 .parent();

$(".DialogHeaderTitleFont").parent().css("width");

请记住,如果您在文档变量中的任何位置重复此类,可能会发生变化,因此我建议您使用某种唯一标识符,例如 id 而不是类

【讨论】:

  • +1 以获得好的答案(尽管我认为.closest 会更好)。 -1 表示“建议您使用某种唯一标识符,例如 id”。结果 - 0
  • 使用类来获取特定值不是最佳实践我可以向你保证,除非你真的为 jquery 目的编写该类stackoverflow.com/questions/1230636/…
  • 您假设该类不会在多个地方用于样式目的。
猜你喜欢
  • 2013-06-23
  • 2016-08-09
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 2015-12-09
相关资源
最近更新 更多