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

How to take a href attribute and use it in a div when clicking on it?

在javascript中我想告诉post-container当我点击它时,获取位于link的href并转到第X页。

There are multiple 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>

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

知道怎么做吗?

我希望我能正确解释您的问题,但您可以重新排列您编写 href 标签的位置。相反,将 div 包裹在里面。这将使整个 div 元素成为 link.

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

这将work.Add事件监听到父元素(Event Delegation)。你可以取子元素的href属性然后使用window.location.href。您可能需要添加 preventDefault() 以避免 a 标签

的默认行为

如果您有多个具有相同 class name.You 的标签,则必须使用 querySelectorAll。如果您有单个元素或具有相同 class 名称的多个元素,则使用任何一种方式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>

document.getElementsByClassName('post-container')[0].onclick = function(e){
  location.href = this.children[0].href;
}

Javascript:

var elements = document.getElementsByClassName('post-container');

var loadLink = function() {

    var link = this.getElementsByTagName("a")[0].href;

    window.location.href = link;

};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', loadLink, false);
}

勾选working demo

假设您有多个 .post-container,您将需要遍历每个并添加一个事件侦听器来处理点击事件。单击时,找到 a 获取它的 href 并设置 window.location(我只是在这个演示中控制台登录它)

(function(){
    let elems = document.querySelectorAll(".post-container");
    for (i = 0; i < elems.length; ++i) {
        let el = elems[i];
        el.addEventListener("click", function(e) {
            e.preventDefault();
            let href = el.querySelector("a").getAttribute("href");
            console.log("href",href);
            //window.location.href = href;
        })
    }
})();
<div class="post-container">
  <a class="link" href="X">
    <h2 class="post-title">Hello, world!</h2>
  </a>
  <div class="date-posts">...</div>
</div>
<div class="post-container">
  <a class="link" href="Y">
    <h2 class="post-title">Goodbye world!</h2>
  </a>
  <div class="date-posts">...</div>
</div>