尝试执行 a:active 以保持打开状态,直到单击其他链接

Trying to do a:active to stay on untill other link is clicked

本文关键字:状态 链接 其他 单击 执行 active      更新时间:2023-09-26

我想做的是:我有两个链接热/更新。单击热时,它应变为红色并更新为黑色。单击更新时,它应该变成红色和热变成黑色。

这适用于小提琴,但不适用于我的网站。

我能够在SO上找到各种答案,因为这似乎是一件很常见的事情。我正在一个接一个地实施,但没有一个有效。它们似乎在小提琴中工作正常,但在我的网络上却不能。

.HTML:

<div id="Space" >
  <ul>
    <li role="presentation" class="sort">
      <a class="link" href="/?sort=score&page=1" style="text-decoration:none;">hot</a>
    </li>    
    <li role="presentation" class="date">
      <a class="link" href="/?sort=date&page=1" style="text-decoration:none;">update</a>
    </li>
  </ul>
</div>

JavaScript:

$(function() {
  var links = $('a.link').click(function() {
    links.removeClass('active');
    $(this).addClass('active');
  });
});

.CSS:

a.link.active { color: red; }
a, a:visited { color: black }

现在,这做了a:active做的事情,它不会保持红色。

var links =不会做你认为它做的事情。

您认为它正在这样做:

var links = $('a.link');

但是,由于您将其分配给实际的点击事件,因此不会生成该选择器。

您需要按如下方式修改代码:

// This is a "safer" document ready, to prevent conflicts with other $ libraries
jQuery(function($) {
  $('a.link').click(function() {
    // Remove the class from all other links
    $('a.link').removeClass('active');
    // Add the class to _just this link_
    $(this).addClass('active');
  });
});

或者,保留var links的版本:

// This is a "safer" document ready, to prevent conflicts with other $ libraries
jQuery(function($) {
  // Assign all links to the "links" variable
  var links = $('a.link');
  links.click(function() {
    // Remove the class from all other links
    links.removeClass('active');
    // Add the class to _just this link_
    $(this).addClass('active');
  });
});

这是一个工作小提琴:https://jsfiddle.net/cale_b/tqzt8f7s/1/

因此,

为了澄清,您希望根据URL是否具有特定查询来突出显示某些按钮。如果 url 包含/?sort=score&page=1,则突出显示排序,如果 url 包含/?sort=date&page=1,则突出显示日期。

为此,您需要做的就是在页面(window.location.search)中搜索每个字符串。这样的事情的代码将是。

const highLightWhat = (window.location.search).search('sort=score') !== -1 ? 'Highlight sort' :
    (window.location.search).search('sort=date') !== -1 ? 'Highlight date' :
    'Highlight Nothing';

然后,此标志可用作突出显示一个"a"标签或另一个标签的参考。

我希望这有帮助!(:

试试这个javaScript一次

$(function() {
   $('a.link').click(function(event) {
            event.preventDefault();
       $('a.link').removeClass('active');
       $(this).addClass('active');
   });
});