Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jquery将类添加到当前a标记,而不是div中的所有a标记_Jquery - Fatal编程技术网

jquery将类添加到当前a标记,而不是div中的所有a标记

jquery将类添加到当前a标记,而不是div中的所有a标记,jquery,Jquery,我想向当前链接添加一个“活动”类,我有以下代码: jquery: $("#products a").each(function() { if(this.href == window.location || this.href == document.location.protocol + "//" + window.location.hostname + window.location.pathname) $(this).addClass("selectedThumb"); })) html:

我想向当前链接添加一个“活动”类,我有以下代码:

jquery:

$("#products a").each(function() {
if(this.href == window.location || this.href == document.location.protocol + "//" + window.location.hostname + window.location.pathname)
$(this).addClass("selectedThumb");
}))

html:

<div id="products">
  <a>First product</a>
  <a>Second product</a>
</div>

第一产品
第二产品
我想以当前链接结束,点击后添加“selectedThumb”类。现在,该类被添加到所有的a标记中,我的结论是:

<div id="products">
  <a class="selectedThumb">First product</a>
  <a class="selectedThumb">Second product</a>
</div>

第一产品
第二产品
这是一个产品图像缩略图查看器,因此我始终停留在当前页面上,在单击a链接后不离开页面,而是在页面上更改产品缩略图。这个代码很好用。不确定这是否与smth有关

附加信息

我试图添加“active”state/css类的a标记是thumb图像,当鼠标悬停时,它有一个mouseover事件,在该页面中显示该thumb,而thumb没有链接

mouseover事件调用显示正确产品图像的JS函数

它调用的JS:

function displayImage(index, parent){
var images = document.getElementById(parent).getElementsByTagName("div");

for(var i = 0; i < images.length; i++) {
  var image = images[i];
  if (image.className != 'pimage')  { continue }
  if(i == index-1) {
    image.style.display="block";
  }
  else {
    image.style.display="none";
  }     
}   
函数显示图像(索引,父级){
var images=document.getElementById(父级).getElementsByTagName(“div”);
对于(var i=0;i
}


因此,由于a链接实际上没有链接到任何地方,jQuery addClass被添加到所有缩略图链接中。

可能会尝试匹配url(未测试):


我会尽量在你的代码中更清楚你想做什么。如果试图仅将类应用于某个链接,则仅选择该链接:

$('#products a[href="' + window.location.href + '")
    .addClass('selectedThumb')
;
如果这是您特别需要经常选择的内容,那么扩展jQuery可能会很好:

$.extend($.expr[':'], {
    currentPage: function(el) {
        return el.href && el.href === window.location.href;
    }
});

// then...
$('a:currentPage').addClass('selectedThumb');

loc.match(this.href)
不是一个好的比较器<代码>”http://example.com/some/deep/link“.match(”http://example.com“”==true
是的,我假设他使用的是相对路径=/wow,感谢您的快速回复!我在代码中添加了更多的细节,希望对您有所帮助@nick,我尝试了你的例子,但出于某种原因,它无法正常工作。
标记应该始终具有
href
属性(除非你将它们用作命名锚,这里不是这样)。如果没有
href
,浏览器将不会将它们呈现为链接(也不会应用悬停事件等)。常用的方法是设置
href=“#”
$.extend($.expr[':'], {
    currentPage: function(el) {
        return el.href && el.href === window.location.href;
    }
});

// then...
$('a:currentPage').addClass('selectedThumb');