动态生成的href值从Popover正文锚点消失问题排查
弹出框(Popover)链接href丢失问题
我做了一个包含两个锚点的Popover:一个在标题区域,一个在正文区域,两者都是用来打开或下载对应图片的。因为用户会创建新图片,且图片的ID是通过Flask从数据库加载的,所以我用JQuery动态生成href值。
最初问题
代码能成功给两个锚点的href赋值,但点击Popover后,标题里的链接正常工作,正文里的链接却失效了。查看页面元素发现,正文锚点的href值直接消失了。
以下是我写的代码:
JavaScript 代码
$(document).ready(function(){ $('.image-options').click(function() { var icon_id = $(this).attr('id'); icon_id = "#" + icon_id img_id = icon_id + "mg"; the_url = $(img_id).attr('src'); var popString2 = ""; popString2 = popString2 + "<a href='" + the_url + "' class='options' id='saveImage'>Save image <span class='icon-pop'><i class='fa-regular fa-floppy-disk'></i></span></a>"; $(icon_id).attr('data-bs-content', popString2); var popString1 = ""; popString1 = popString1 + "<a href='" + the_url + "' class='options' id='addCollection'>Add to collection <span class='icon-pop'><i class='fa-solid fa-plus'></i></span></a>"; $(icon_id).attr('data-bs-original-title', popString1); }); });
HTML 代码
<!-- 图片ID从数据库加载,格式是数字加'img',比如121img --> <img class="card-img-top card-img-bottom thumb" data-bs-toggle="modal" data-bs-target="#myModal" src="{{ url_for('static',filename=image[1]) }}" id="{{ image[0] ~ 'img' }}"> <!-- Popover的ID是数字加'i',比如121i --> <a class="btn-opt btn-sm image-options" data-bs-container="body" data-bs-toggle="popover" data-bs-placement="left" data-bs-html="true" id="{{ image[0] ~ 'i' }}"><i class="fa-solid fa-ellipsis"></i></a>
更新后的问题
我移除了Popover标题里的href,只保留正文的链接。现在新问题出现:第一个Popover的链接正常,但打开第二个Popover时,它的正文锚点href消失了(锚标签还在,只有href没了),感觉存储URL的变量the_url只能用一次。
更新后的JavaScript代码:
$(document).ready(function(){ $('.image-options').click(function() { var icon_id = $(this).attr('id'); icon_id = "#" + icon_id; img_id = icon_id + "mg"; the_url = $(img_id).attr('src'); var popString2 = ""; popString2 = popString2 + "<a href='" + the_url + "' class='options'>Save image <span class='icon-pop'><i class='fa-regular fa-floppy-disk'></i></span></a>"; $(icon_id).attr('data-bs-content', popString2); var popString1 = ""; popString1 = popString1 + "<a class='options'>Add to collection <span class='icon-pop'><i class='fa-solid fa-plus'></i></span></a>"; $(icon_id).attr('data-bs-original-title', popString1); }); });
内容的提问来源于stack exchange,提问作者br1saturno
相关产品推荐
相关产品推荐

