如果类名和窗口位置匹配,请执行一些操作

If class name and window location match, do something

本文关键字:执行 操作 窗口 位置 如果      更新时间:2023-11-19

如果单击的类名与当前URL同名,则等同于true。以下是我目前的使用方式:

$('a.archive').click(function(){
   if (window.location == www.google.com/archive.php)
  // do something
else {
  // do default
     }
});

但是,我不想在每个if语句中编写不同的URL。我想找到一种方法来匹配位置:www.google.com/archive.php与单击的类名:存档

所以理想情况下,我可以写这篇文章:

$('a.archive').click(function(){
 if (URLandClassNameMatch).
      // do something
    else {
      // do default
         }
});

我会这样想吗?

$("a").click(function(ev)
{
   var classes = ($(this).attr('class') || "").split(" ");
   $.each(classes, function(index, value)
   {
       if (window.location.href.indexOf("/"+value+".php") != -1)
          // doSomething
   });
});

这可能是您想要的

http://jsfiddle.net/KDLjf/82/

检查这个小提琴以及你的意见

http://jsfiddle.net/KDLjf/83/

$('a.archive').click(function(){
    var url="www.google.com/"+$(this).attr('class')+".php";
    alert(url);
 if (window.location==url) // so if they match, it equates to true.
 {
 alert('Matched')
 }
      // do something
    else {
        alert('Not Matched')
      // do default
         }
});

根据我的理解,我已经做了这样的

var yourclassclass = $('your_id').attr('class');
var regx = new RegExp("[a-z][A-Z].[a-z][A-Z].com/"+yourclassclass+".php");
var URLandClassNameMatch = regx.exec(yourURL.search);
if (URLandClassNameMatch).
   // do something
else {
   // do default
}

如果您从"window.location"获取URL,则将您的URL替换为"window.locations"。