【问题标题】:Apply href to div based on another element基于另一个元素将 href 应用于 div
【发布时间】:2020-06-05 04:53:51
【问题描述】:

编辑 - 我最初忽略了我无权更改标记的声明。

我对 jQuery 不是很好,所以我没有成功地让它工作。我需要从 entry-title 标题中获取 href 并将其应用于 entry-content div。

<h3 class='slide-entry-title entry-title'><a href='/test-page' title='Slide 1'>Slide 1</a></h3>
<div class='slide-entry-excerpt entry-content'>
    <p><img src="/img/test-image.jpg" /></p>
</div>

这需要对页面上尽可能多的幻灯片执行此操作,每个幻灯片都有自己独特的 href。其他幻灯片的类名不会更改。

我找到了用于单击项目的此代码,但我不是在等待单击...我需要自动应用它。

$(".entry-content").click(function() {
  window.location = "http://yahoo.com";
});

【问题讨论】:

  • 将您的 href 添加为 data 属性并使用 $().data('my-link') 函数访问它
  • 请参阅上面的说明...我无法修改标记。

标签: jquery href


【解决方案1】:

你只需要找到之前.entry-title 的url 并使用它而不是"http://yahoo.com" 试试这个:

$(".entry-content").click(function () {
        let url = $(this).prev(".entry-title").children('a').attr('href');
        window.location = url;
});

【讨论】:

  • 感谢您的建议。我相信我需要使用 .click() 以外的东西对吗?我希望它在加载时发生,所以也许 .ready()?
  • @pburgh .ready() 在 DOM 准备好时触发,.click() 一般用于这种事情,你也可以使用.on() 方法或.bind() 方法,示例:$('.entry-content').on('click', function() { /* Do Something */ });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 2016-10-07
  • 2016-07-06
  • 2016-03-25
相关资源
最近更新 更多