如何在此代码片段中定位链接图像而不是链接文本

How to target a linked image instead of linked text in this code snippet?

本文关键字:链接 图像 文本 定位 代码 片段      更新时间:2023-09-26

我想针对链接的图像而不是链接的文本,这是它在以下代码片段中使用此页面上的textContent属性编码的方式:www.ninjasdontsweat.com。我理解的方式是,当页面加载并添加className 'sqs-search-ui-button sqs-search-ui-button-wrapper'到搜索文本周围的元素(在本例中为

元素)。
<script>
//SEARCH
document.addEventListener('DOMContentLoaded', function(){
    var nav = document.querySelectorAll(".main-nav .external-link");
    Array.prototype.forEach.call(nav,function(el,i){
        if (el.textContent.match(/Search/)) {
            el.className += ' sqs-search-ui-button sqs-search-ui-button-wrapper';
        }
    });
});
</script>
<li class="external-link sqs-search-ui-button sqs-search-ui-button-wrapper">
      <a href="/Search">Search</a>
</li>

在我的页面上(见下文),基本上我认为需要发生的是:当点击search.jpg时,JavaScript将做两件事…添加className "sqs-search-ui-button &;到元素,并将其停用。/nandf/"允许CSS像在第一个代码片段中那样覆盖页面。希望这能说得通!如果你有任何问题,请告诉我。

<div class="wrapper">
  
         <a class="project " href="/nandf/" data-ajaxify="false">
           <div>
            <div class="project-image"><div class="intrinsic">
             <div class="content-fill" style="overflow: hidden;">
               <img data-src="http://static.squarespace.com/static/52cd716be4b065c5e52b9967/t/53248d81e4b0d7985481f99d/1394904442216/search.jpg" 
               data-image="http://static.squarespace.com/static/52cd716be4b065c5e52b9967/t/53248d81e4b0d7985481f99d/1394904442216/search.jpg" 
               data-image-dimensions="396x396" data-image-focal-point="0.5,0.5" 
               data-load="false" alt="search" 
               class="" src="https://static.squarespace.com/static/52cd716be4b065c5e52b9967/t/53248d81e4b0d7985481f99d/1394904442216/search.jpg?format=300w" 
               data-image-resolution="300w" style="top: 0px; left: 0px; width: 282px; height: 282px; position: relative;"></div></div><div class="project-item-count">1</div></div>
            <div class="project-title">search</div>
           </div>
        </a>
</div> 

您还需要在元素内搜索图像:

var nav = document.querySelectorAll(".main-nav .external-link");
Array.prototype.forEach.call(nav,function(el,i){
  if(matches(el)) {
    el.className += ' sqs-search-ui-button sqs-search-ui-button-wrapper';
  }
});
function matches(el) {
  if (el.textContent.match(/Search/)) {
    return true;
  }
  var images = el.getElementsByTagName("img");
  return Array.prototype.some.call(images, function(img) {
    return img.src.match(/search/);
  });
}

如果您有更多的标准(例如匹配图像的title),您只需要将它们添加到matches函数