单击时如何获取href属性并在div中使用它?

问题描述:

在javascript中,我想告诉post-container,当我单击它时,请使用位于link的href并转到第X页.

In javascript I want to tell post-container that when I click on it, take the href located at link and go to page X.

有多个post-container

我的代码是这样的:

<div class="post-container">
  <a class="link" href="X">
    <h2 class="post-title">Hello, world!</h2>
  </a>
  <div class="date-posts">...</div>
</div>

我希望能够在post-container的任何区域中点击帖子的Hello, world!标题之外并转到第X页

I want to be able to click outside the Hello, world! title of my post in any area of ​​post-container and go to page X

知道如何执行此操作吗?

这将起作用.将事件侦听器添加到父元素(

This will work.Add Event listener to the parent element (Event Delegation).You can take the href property of the child element and then use window.location.href.You might need to add preventDefault() to avoid default behaviour of a tag

如果有多个具有相同类名的标记,则必须使用querySelectorAll.如果您具有单个元素或具有相同类名的多个元素,则可以使用querySelctorAll.

If you have multiple tags with same class name.You have to use querySelectorAll .Either way if you have single elements or multiple elements with same class name use querySelctorAll.

// if you have one tag
let ele = document.querySelectorAll(".post-container")
ele.forEach(element => {
  element.addEventListener("click", function(e) {
    e.preventDefault();
    let href = element.children[0].getAttribute("href")
    window.location.href = href;

  })

})

.post-container {
  background-color: green;
}

<div class="post-container">
  <a class="link" href="X">
    <h2 class="post-title">Hello, world!</h2>
  </a>
  <div class="date-posts">...</div>
</div>