如何用jQuery将SVG内a标签的href转换为xlink:href?
I feel your pain—Safari's stubbornness with SVG links combined with Drupal's security filters can be super frustrating. Let's get this sorted with a reliable jQuery solution that works even with dynamic Views content.
Here's the step-by-step fix:
Since Drupal's security layer strips out the xlink:href attribute, we'll add it back client-side. The key is to target SVG links specifically, handle both initial page load and AJAX-updated Views content, and ensure the required XLink namespace is present.
1. Use Drupal Behaviors (Best Practice for Drupal)
Drupal's behaviors system is perfect here because it automatically runs when the page loads and after any AJAX updates (like when your Views refreshes or loads more content). Add this code to your theme's js file or a custom module's JS:
Drupal.behaviors.fixSvgLinks = { attach: function(context, settings) { // Target all <a> tags inside SVG elements, limited to the current context $('svg a', context).each(function() { var $link = $(this); var originalHref = $link.attr('href'); // Only proceed if href exists and xlink:href isn't already set if (originalHref && !$link.attr('xlink:href')) { // Add the xlink:href attribute with the original href value $link.attr('xlink:href', originalHref); // Ensure the SVG has the required XLink namespace declaration var $svg = $link.closest('svg'); if (!$svg.attr('xmlns:xlink')) { $svg.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink'); } } }); } };
2. Why this works:
- Context-aware: The
contextparameter ensures we only process new content added via AJAX, not reprocess existing elements. - Namespace fix: Safari requires the
xmlns:xlinkattribute on the SVG element to recognizexlink:href—we add it if it's missing. - Idempotent: We check if
xlink:hrefalready exists to avoid redundant work.
3. If you're not using Drupal Behaviors (for standalone jQuery):
If you just need a basic fix for non-AJAX content, use this inside a DOM ready handler:
$(document).ready(function() { $('svg a').each(function() { var $link = $(this); var href = $link.attr('href'); if (href) { $link.attr('xlink:href', href); var $svg = $link.closest('svg'); if (!$svg.attr('xmlns:xlink')) { $svg.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink'); } } }); });
Common pitfalls to avoid:
- Forgetting AJAX content: If your Views loads content dynamically (like infinite scroll or filters), the basic DOM ready code won't catch new SVG links—use the Drupal Behaviors version instead.
- Missing namespace: Without
xmlns:xlinkon the SVG, Safari still won't recognizexlink:href, even if you add the attribute. - Targeting the wrong elements: Make sure you're selecting
<a>tags inside<svg>elements, not regular HTML links.
内容的提问来源于stack exchange,提问作者user3716886

