首页 > 解决方案 > 如何使从 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

标签: javascriptjqueryhtmljsonappend

解决方案


您应该使用静态元素作为启动器,然后在 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');
    });

推荐阅读