【问题标题】:Find <iframe> width and height查找 <iframe> 的宽度和高度
【发布时间】:2021-03-16 19:48:44
【问题描述】:

我有一个这样的对象:

object = {
    iframe: "<iframe width="560" height="315" src="YouTube link"></iframe>"
}

我需要使用 jQuery/js 获取其中的宽度(在本例中为 560)和高度(在本例中为 315)值。因为我需要使用这个值。

这可能吗?

谢谢。

【问题讨论】:

  • 在您的示例中,object.iframe 是字符串、元素还是 jQuery 对象..?不清楚
  • 注意:字符串无效 - 字符串中的引号没有被转义。使用反斜杠 (\") 转义它们或使用不同类型的引号
  • 嗨@RoryMcCrossan,是的,字符串是object.iframe

标签: javascript jquery iframe


【解决方案1】:

您可以使用正则表达式来隔离两个参数:

var object = {
    iframe: '<iframe width="560" height="315" src="YouTube link"></iframe>' // string was invalid before, replaced quotes with apostrophes
}
var regexFound = object.iframe.match(/width="(\d*?)" height="(\d*?)"/);
var asArray = [regexFound[1], regexFound[2]];
var asObject = {width: regexFound[1], height: regexFound[2]}
console.log(asArray, asObject);

【讨论】:

  • 谢谢柠檬!这就是我需要的。
【解决方案2】:

首先注意示例中的字符串由于重复使用"而无效。要使字符串有效,请使用' 对其进行分隔,并使用" 将属性值包含在其中。

当您使用 jQuery 标记问题时,您可以使用它从字符串构建对象,而不是使用正则表达式解析它:

let object = {
  iframe: '<iframe width="560" height="315" src="YouTube link"></iframe>'
}

let $iframe = $(object.iframe);

console.log($iframe.prop('width'));
console.log($iframe.prop('height'));
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 非常感谢罗里!不错的 jQuery 解决方案。
  • 没问题,很高兴为您提供帮助。请注意,使用正则表达式解析 HTML 是非常糟糕的做法,并且可能导致其他问题。
  • 感谢罗里的信息,我很感激。我永远不会停止学习。
猜你喜欢
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 2011-12-10
  • 2016-08-09
相关资源
最近更新 更多