单击时如何获取href属性并在div中使用它? [英] How to take a href attribute and use it in a div when clicking on it?

查看:133
本文介绍了单击时如何获取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>

这篇关于单击时如何获取href属性并在div中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆