确保svg是要引用的对象标记的外部文件。出于某种原因,我无法获得" Layer_1"通过id。我可以获得svgElem和svgDoc,但不能获得" Layer_1"通过svg文件中的id。
(function($) {
$(window).load(function() {
var svgElem = document.getElementById("test-svg"); //returns value
alert("svgElem=" + svgElem); //returns value
var svgDoc = svgElem.contentDocument;
alert("svgDoc = " + svgDoc); //returns value when svg external file
var layer1 = svgDoc.getElementById("Layer_1");
alert("layer1 = " + layer1); //returns null* This is my problem.
});
})(jQuery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<div id="container">
<div id="container2">
<object id="test-svg" type="image/svg+xml" data="svg-layer-test.svg">
<!-- PLEASE MAKE THIS SVG AN EXTERNAL DOCUMENT and name file 'svg-layer-test.svg'-->
<!--<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 91.333 70.667" enable-background="new 0 0 91.333 70.667" xml:space="preserve">
<g id="Layer_1">
<text transform="matrix(1 0 0 1 -4.333 68.6665)" font-family="'TimesNewRomanPS-BoldMT'" font-size="100" id="first_date">13</text>
</g>
<g id="Layer_2">
<text transform="matrix(1 0 0 1 -4.333 68.6665)" font-family="'TimesNewRomanPS-BoldMT'" font-size="100">15</text>
</g>
</svg>-->
</object>
</div>
</div>
</body>
</html>
&#13;