javascript - jQuery 我想将事件类添加到 anchor 标记的链接 ID

标签 javascript jquery list

我写了一个字母导航程序 - 我有链接到 h4 标签的 anchor 。当我单击 a 标签时,我希望具有匹配 ID 的元素具有事件类。当您单击另一个 anchor 标记时,它会删除事件类并将其分配给另一个元素。这是我到目前为止所拥有的:

<ul class="no-bullet inline">
            <li><a class="scroller" href="#a"><strong>A</strong></a></li>
            <li><a class="scroller" href="#b"><strong>B</strong></a></li>
            <li><a class="scroller" href="#c"><strong>C</strong></a></li>

          </ul>

<h4 class="alpha-heading" id="a"><strong>A</strong></h4>

<h4 class="alpha-heading" id="b"><strong>B</strong></h4>

<h4 class="alpha-heading" id="c"><strong>C</strong></h4>


$("scroller").on("click", function(){
function matchAlpha(){
var matchID = $(this).attr("href");
find.$(matchID).find.$(alpha-heading).removeClass("active");
find.$(matchID).find.$(this).$(alpha-heading).addClass("active");
}

});

最佳答案

您可以将点击处理程序中的代码缩减为一行:

$('.scroller').click(function() {
  $($(this).attr('href')).addClass('active').siblings().removeClass('active')
})
.active {
  background: #faa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="no-bullet inline">
  <li><a class="scroller" href="#a"><strong>A</strong></a></li>
  <li><a class="scroller" href="#b"><strong>B</strong></a></li>
  <li><a class="scroller" href="#c"><strong>C</strong></a></li>

</ul>

<h4 class="alpha-heading" id="a"><strong>A</strong></h4>

<h4 class="alpha-heading" id="b"><strong>B</strong></h4>

<h4 class="alpha-heading" id="c"><strong>C</strong></h4>

其工作方式如下:

  • $('.scroller').click(function() {:点击带有scroller类的链接时
  • $(this).attr('href') 获取href属性
  • 选择它并使用 .addClass('active') 添加事件类
  • 选择该元素的所有同级元素,并使用 .siblings().removeClass('active') 删除事件类

关于javascript - jQuery 我想将事件类添加到 anchor 标记的链接 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45306883/

相关文章:

javascript - SweetAlert2 - 如果有一个按钮,模式一打开它就会突出显示

javascript - FullCalendar 自定义按钮图标未显示

javascript - 如何删除具有特定子项的 jQuery 中的元素?

javascript cloneNode() 无法正常工作

jquery - 为什么 Blueimp 的 jQuery-File-Upload 插件不触发回调?

vb.net - VB : Is it possible to cast/convert from List(Of DataRow) to List(Of String)?

javascript - html5音频所需的一些代码帮助

javascript - 我可以从 Google 自定义搜索 API 获取 Google Ads 来满足所请求的查询吗?

python - 元素更改后列表不会更改

python - 如果可以向元组添加 (a += (3,4)),那么元组如何不可变