簡體   English   中英

如何使從JSON添加的鏈接可點擊?

[英]How to make links added from JSON clickable?

我正在嘗試附加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');
    });

在注入新鏈接之前,必須將單擊委托給頁面中存在的父元素。

jQuery的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');
});

了解更多: http : //api.jquery.com/on/#direct-and-delegated-events

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM