簡體   English   中英

添加事件監聽 JS

[英]Add event listener JS

我是 JS 新手。 我正在嘗試在 onclick 事件偵聽器上編寫 function 以獲取 # 值並將該值傳遞給另一個 function。 你能幫我么。 當用戶嘗試單擊 a 標簽時,我想捕獲 # 值並將 href 值傳遞給下面的 function 以進行滾動頂部偏移

<ul class="scrolltop scrolltop">
  <li>
    <a href="#Covered">What’s covered</a>
  </li>
  <li>
    <a href="#Collect">Personal Information</a>
  </li>
</ul>
var tabScroll = document.querySelector("#Collect")
window.scrollTo({
  'behavior': 'smooth',
  'left': 0,
  'top': tabScroll.offsetTop - 110
});

對於事件監聽器,我推薦 jquery; 它應該看起來像這樣。

$(document).on('click', 'a', function() {
    href_val = $(this).attr('href');
    myFunction(href_val);
});

用純 Javascript 編寫的解決方案:

 document.querySelectorAll('a').forEach(function(element) { // Get all a elements and perform action on them element.addEventListener('click', function() { // Do something }) })
 <ul class="scrolltop scrolltop"> <li> <a href="#Covered">What's covered</a> </li> <li> <a href="#Collect">Personal Information</a> </li> </ul>

如果您需要在每個中獲取 href 值,您可以執行以下操作:

 const tabScroll = document.getElementsByTagName("a") // Here you add the events: const hola = [...tabScroll].forEach(link => link.addEventListener("click", getLinkValue)); // Here you pass the scroll element to the scrollTo function function getLinkValue(event){ const linkElement = event.target; const hrefValue = linkElement.href.split("#")[1]; const hrefWithHash = `#${hrefValue}` window.scrollTo({ 'behavior': 'smooth', 'left': 0, 'top': linkElement.offsetTop - 110 }); }
 <ul class="scrolltop scrolltop"> <li> <a href="#Covered">What's covered</a> </li> <li> <a href="#Collect">Personal Information</a> </li> </ul>

暫無
暫無

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

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