【问题标题】:How to redirect user to new page on div click JQuery [duplicate]如何将用户重定向到 div 上的新页面单击 JQuery [重复]
【发布时间】:2019-01-07 18:05:38
【问题描述】:

如何根据点击的 div 加载新 URL。每个 div 都有自己的加载 URL(在我的实现中,div 是博客页面)。

我的 JQuery: & 我的 html:

$('.postWraper').click(() => {
        window.location = $(this).find('h3').find('a').attr('href');
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="postWraper">
    <h3 class="postTitleH3">
        <a href="blog/first-page" class="postTitle">
            <%= post.postTitle %>
        </a>
    </h3>
</div>
<div class="postWraper">
    <h3 class="postTitleH3">
        <a href="blog/second-page" class="postTitle">
            <%= post.postTitle %>
        </a>
    </h3>
</div>

当我点击第一个或第二个 div 时,它总是将我重定向到第一个 URL。我不明白为什么。请帮忙!

【问题讨论】:

  • 也许你的 html 是坏的或错误的?
  • 这不是浏览器的默认行为吗?你为什么要为它写一个脚本?
  • 运行代码时,$(this).find('h3').find('a').attr('href') 正在返回 undefined

标签: javascript jquery html


【解决方案1】:

meaning of this 已更改,因为您使用箭头函数作为事件处理程序。将其更改为常规函数:

$('.postWraper').click(function() {
    window.location = $(this).find('h3').find('a').attr('href');
    return false;
});

【讨论】:

    【解决方案2】:

    您不一定需要更改箭头功能。您仍然可以通过在click 事件中传递事件对象并使用e.target.href; 获取href 值来使其工作:

    $('.postWraper').click((e) => {
      window.location = e.target.href;
      return false;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="postWraper" id="<%= post.id %>">
        <h3 class="postTitleH3">
            <a href="blog/first-page" class="postTitle">
                Some title
            </a>
        </h3>
    </div>
    <div class="postWraper">
        <h3 class="postTitleH3">
            <a href="blog/second-page" class="postTitle">
                Some title
            </a>
        </h3>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多