在nth-Child Div中将图像作为点击链接



im尝试使用jQuery在我的Squarespace站点上添加一个链接。但是,他们不共享一堂课,我不能使用Squarespace添加一个作为即时通讯,因此我只能添加自定义CSS或JavaScript。

因此,即时试图这样做的方式是选择具有" .prouctuctItem-gallery-slides-item"类名称的父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>

最新更新