简体   繁体   English

如果此href包含var

[英]if this href contains a var

Trying to check if href contains a var. 尝试检查href是否包含变量。 No luck so far 到目前为止没有运气

  var navcur = window.location.href;
  $(".subnavli").each(function(){
    if ($(this).find("a[href=" + navcur + "]")) {alert('works!');}  
  });

Since the href have special chars you need to wrap the attribute value. 由于href具有特殊字符,因此您需要包装属性值。 Also .find() returns a jQuery object irrespective of whether a match is found or not so you need to check whether the jQuery object contains any elements - you can check the length property for that 而且.find()会返回一个jQuery对象,而不管是否找到匹配项,因此您需要检查jQuery对象是否包含任何元素-您可以检查该对象的length属性

var navcur = window.location.href;
$(".subnavli").each(function () {
    if ($(this).find("a[href='" + navcur + "']").length) {
        alert('works!');
    }
});

It can be simplified using descendant selector instead of using a loop 可以使用后代选择器而不是循环来简化

var navcur = window.location.href;
var $a = $(".subnavli a[href='" + navcur + "']");
if ($a.length) {
    alert('works!');
}

this works for me: 这对我有用:

 var navcur = window.location.href

 $(".subnavli").each(function(){      
   if ($(this).attr("href") ===navcur) {alert('works!');}  
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM