javascript - 如何使从 JSON 添加的链接可点击?
问题描述
我正在尝试从 JSON 文件附加链接,但它们onClick
不起作用。
HTML:
<li class="nav-item dropdown" id = "views">
<a class="nav-link dropdown-toggle" id="view-type" data-toggle="dropdown" data-selected="high_level" aria-haspopup="true" aria-expanded="false">High Level View</a>
<div class="dropdown-menu" aria-labelledby="view-type" style="height: 35vh; overflow: auto;">
<h7 class="dropdown-header">View Type</h7>
<a class="dropdown-item filter-option active" href="javascript:void(0);" id="high_level">High Level View</a>
</div>
</li>
Javascript:
d3.json(theURL, function(error, data) {
if (error) throw error;
var unique = [];
data.forEach(function(e){
if(unique.indexOf(e.segment) == -1){
unique.push(e.segment);
}
});
unique.forEach(d =>
$('#views .dropdown-menu').append(`<a class="dropdown-item filter-option ecodes" href="javascript:void(0);" id="${d.substring(0, 4)}">${d}</a>`)
)
if($('#all').hasClass('active') == true) {
$('.ecodes').remove();
}
});
$('.filter-option').on('click', function() {
let text = $(this).text();
let selected = $(this).prop('id');
$(this).parent().parent().children('a').text(text);
$(this).parent().parent().children('a').data().selected = selected;
filters[$(this).parent().parent().children('a').prop('id').replace('-','_')] = selected;
$.each($(this).parent().children('a'), function(i,d)
$(d).removeClass('active'); });
$(this).addClass('active');
});
我的代码有问题吗?我似乎无法弄清楚为什么我的链接不起作用。我需要onClick
他们上课active
。
解决方案
您应该使用静态元素作为启动器,然后在 on 方法中委派动态节点(子节点)
$('dropdown-menu').on('click','.filter-option', function() {
let text = $(this).text();
let selected = $(this).prop('id');
$(this).parent().parent().children('a').text(text);
$(this).parent().parent().children('a').data().selected = selected;
filters[$(this).parent().parent().children('a').prop('id').replace('-','_')] = selected;
$.each($(this).parent().children('a'), function(i,d)
$(d).removeClass('active'); });
$(this).addClass('active');
});
推荐阅读
- amazon-kinesis - 如何使用 kinesis 分析创建排行榜查询
- amazon-web-services - 亚马逊连接:可以选择区号,一个主机可以多于一个免费实例吗?
- sql - 使用与总计数列不同的过滤器注入另一列中的值的总和
- android - Android 无障碍服务单元测试
- gitlab - 在 gitlab docker 注册表中使用 minio
- symfony - QueryBuilder - 在 innerJoin 中使用 Select
- css - Materialize - 就像触发sidenav一样消失
- android - 清单文件中缺少 Cordova 相机权限
- node.js - 运行 node index.js 什么都不做
- android - 耳机按钮单击时应用程序崩溃