根据元素 ID 从数据部分获取值

Get value from data-section based on element ID

我想在页脚部分的 h2 中动态呈现部分 id="zero" data-section value。由于我所有的页面都有不同的数据部分值,我希望我们可以定位部分 id="zero"。这样我就可以在我的网站上只使用一个页脚。我只是不精通 javascript 或 jQuery 来正确分配和调用。我知道有 document.getElementById('zero') 但是然后从数据部分获取值并将它出现在我的 H2 中我不清楚。

<section id="zero" class="section-wrap" data-section="Page Name"></section>

<section id="footer">
<h2></h2>
</section>

这里有一些 Javascript 应该有所帮助。

//Get the data-section value
let val = document.getElementById('zero').dataset.section; 

//find the first h2 inside footer section
let header = document.getElementById('footer').getElementsByTagName("h2")[0];

//set the value
header.textContent = val; 

普通 JS 方式

function start(){

  // Find element with id="zero"
  const section = document.querySelector('#zero');

  // Find the h2 element nested inside an element with id="footer"
  const footer = document.querySelector('#footer h2');

  // Get value of data-section attribute
  const dataSectionValue = section.getAttribute('data-section');

  // Set value in your h2 tag
  footer.innerText = dataSectionValue;
}

window.onload = start;

jQuery 方式

$(document).ready(function(){
  const section = $('#zero');

  $('#footer h2').text(section.data('section'));
});