Tôi đang tạo động các phần tử SVG từ JavaScript. Nó làm việc tốt cho các đối tượng trực quan như một hình chữ nhật, nhưng tôi đang gặp khó khăn trong việc tạo ra các xlinks hoạt động. Trong ví dụ bên dưới hình chữ nhật đầu tiên (được định nghĩa tĩnh) hoạt động chính xác khi được nhấp vào, nhưng hai cái khác (được tạo bằng JavaScript) bỏ qua các nhấp chuột ... mặc dù việc kiểm tra các phần tử trong Chrome có vẻ hiển thị cùng cấu trúc.Tạo liên kết SVG động trong JavaScript
Tôi đã nhìn thấy nhiều câu hỏi tương tự xuất hiện, nhưng không có câu hỏi nào chính xác giải quyết vấn đề này. Tôi tìm thấy gần nhất là [adding image namespace in svg through JS still doesn't show me the picture] nhưng không hoạt động (như được ghi chú bên dưới). Mục tiêu của tôi là làm điều này hoàn toàn bằng JavaScript, không phụ thuộc vào JQuery hoặc các thư viện khác.
<!-- Static - this rectangle draws and responds to click -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svgTag">
<a xlink:href="page2.html" id="buttonTemplate">
<rect x="20" y="20" width="200" height="50" fill="red" class="linkRect"/>
</a>
</svg>
<script>
var svgElement = document.getElementById ("svgTag");
// Dynamic attempt #1 - draws but doesn't respond to clicks
var link = document.createElementNS("http://www.w3.org/2000/svg", "a"); // using http://www.w3.org/1999/xlink for NS prevents drawing
link.setAttribute ("xlink:href", "page2.html"); // no improvement with setAttributeNS
svgElement.appendChild(link);
var box = document.createElementNS("http://www.w3.org/2000/svg", "rect");
box.setAttribute("x", 30);
box.setAttribute("y", 30);
box.setAttribute("width", 200);
box.setAttribute("height", 50);
box.setAttribute("fill", "blue");
link.appendChild(box);
// Dynamic attempt #2 (also draws & doesn't respond) - per https://stackoverflow.com/questions/6893391
box = document.createElementNS("http://www.w3.org/2000/svg", "rect");
box.setAttribute("x", 40);
box.setAttribute("y", 40);
box.setAttribute("width", 200);
box.setAttribute("height", 50);
box.setAttribute("fill", "green");
box.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', "page2.html");
svgElement.appendChild(box);
mỗi nhận xét trong các liên kết, tôi đã thử nó với setAttributeNS là tốt. Có vẻ như vấn đề là tôi đang sử dụng không gian tên sai (svg thay vì xlink). – user2837568