javascript - 使第 n-child div 中的图像成为点击链接

标签 javascript jquery html squarespace

我正在尝试使用 jquery 添加指向我的 squarespace 网站上的多个图像的链接。然而,他们不共享一个类,我无法添加一个类,因为我使用的是 squarespace,所以我只能添加自定义 css 或 javascript。

因此,我尝试执行此操作的方法是选择类名称为“.ProductItem-gallery-slides-item”的父 div,然后选择其第二个子 div(也是一个 div),然后选择其中的图像。一旦我选择了正确的元素,我就会添加一个点击功能,该功能应该链接到包含有关图像的更多信息的页面。我已经尝试过使用 .warp() 的另一种方法,但我对 jquery 很陌生,我不太理解它也没有工作。

html 层次结构:

<div class="ProductItem-gallery-slides-item">
  <div>
    <img 1>
  </div>
  <div>
    <img 2>
  </div>
</div>

我的 JavaScript:

$(document).ready(function() {
    $(".ProductItem-gallery-slides-item:nth-child(2)").children('img').click(function(){
      window.location = 'https://uk5-shop.com/paris-pink';
    });
  }

结果应该是可点击的图像。

希望我问得对,非常感谢任何问候。亲切的问候

最佳答案

您的选择器不正确。使用

$(".ProductItem-gallery-slides-item > div:nth-child(2) > img").on("click", ...

因为您想要获取 ProductItem-gallery-slides-item 的第二个子 div。

此外,您的代码缺少结束 )
还有一个旁注:$().click(...) 已弃用。使用 $().on("click", ...) 代替(参见下面的代码)。

演示:

$(document).ready(function(){
    $(".ProductItem-gallery-slides-item > div:nth-child(2) > img").on("click", function(){
        // window.location = 'https://uk5-shop.com/paris-pink';
        // console.log for demo
        console.log("Second image clicked!");
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="ProductItem-gallery-slides-item">
    <div>
        <img src="https://via.placeholder.com/140x100.png">
    </div>
    <div>
        <img src="https://via.placeholder.com/140x100.png">
    </div>
</div>

关于javascript - 使第 n-child div 中的图像成为点击链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56132475/

相关文章:

javascript - 网页动画背后的技术是什么?

javascript - 如何给函数下的属性赋值?

javascript - react native : Component rerender but props has not changed

javascript - 是否可以在 jqGrid 标题行下显示总计(摘要)行?

javascript - 传递动态名称选择器不起作用

html - 单选按钮无法根据样式表进行格式化

javascript - Ember.js:这个方法去哪里了?

jQuery 选择器 - 除第一个之外的所有选择器

javascript - 在 Chrome 扩展中,更改发送到特定域的 ajax 请求的引荐来源网址?

html - cakephp使div成为一个链接