【发布时间】:2020-10-11 04:19:29
【问题描述】:
我一直在努力解决一个相当基本的问题,使用 jQuery (v 1.12.4) 选择器来获取属性值。 HTML 页面包含一个 svg 元素,我尝试为其选择多个属性值:
var svg = $("div.container-fluid > svg").first();
var viewBox = svg.attr("viewBox");
var svgHeight = svg.attr("height");
var svgWidth = svg.attr("width");
var preserveAspectRatio = svg.attr("preserveAspectRatio");
var zoomAndPan = svg.attr("zoomAndPan");
var css = svg.attr("class");
if (typeof(console) != 'undefined') {
console.log("viewBox : " + viewBox + "; height : " + svgHeight + "; width : " + svgWidth + "; preserveAspectRatio : " + preserveAspectRatio + "; zoomAndPan : " + zoomAndPan + "; css class : " + css);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" class="container-fluid"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:v="http://schemas.microsoft.com/visio/2003/SVGExtensions/" width="16.5354in" height="11.6929in" viewBox="0 0 1190.55 841.89"
xml:space="preserve" color-interpolation-filters="sRGB" class="st15" preserveAspectRatio="xMidYMid meet" zoomAndPan="magnify" version="1.1" contentScriptType="text/ecmascript" contentStyleType="text/css">
对于“height”、“width”和“class”属性,.attr() 函数按预期返回值。但是,对于“zoomAndPan”、“preserveAspectRatio”、“viewBox”,.attr() 函数返回“未定义”。在 Chrome 中调试 Javascript 后,我可以看到 svg DOM 结构包含所有预期的属性,因此无法理解问题所在。
任何帮助或想法将不胜感激。
感谢和问候, 安德鲁
【问题讨论】:
-
我将 jQuery 添加到您的 sn-p 中,它似乎工作正常?
-
你的选择器,例如
svg,是一个缩短了实际jQuery选择器的变量吗?外汇。$('.someClass')?如果不是,它与我在 jQuery 中见过的选择器语法完全不同。编辑:运行你的 sn-p,一切似乎都按预期工作?我没有看到任何错误,我看到日志中的所有值都正确显示。
标签: jquery