如何将此元素传递给javascript onclick函数并向该clicked元素添加类 [英] how to pass this element to javascript onclick function and add a class to that clicked element

查看:57
本文介绍了如何将此元素传递给javascript onclick函数并向该clicked元素添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的html导航代码

I had an html navigation code as below

function Data(string) {
  //1. get some data from server according to month year etc.,
  //2. unactive all the remaining li's and make the current clicked element active by adding "active" class to the element
  $('.filter').removeClass('active');
  $(this).addClass('active');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" style="padding-left:21px;">
  <ul class="nav nav-tabs" style="padding-left:40px;">
    <li class="active filter"><a href="#month" onclick="Data('month')">This Month</a></li>
    <li class="filter"><a href="#year" onclick="Data('year')">Year</a></li>
    <li class="filter"><a href="#last60" onclick="Data('last60')">60 Days</a></li>
    <li class="filter"><a href="#last90" onclick="Data('last90')">90 Days</a></li>
  </ul>
</div>

因此从上面的代码中,我要尝试做的是,当用户单击任何选项卡时,所有其余选项卡均应处于非活动状态,而当前的当前元素/选项卡应处于活动状态,但是上述代码未处于活动状态工作,所以任何人都可以让我知道如何使上面的代码工作,还是无论如何,当用户单击选项卡时,我们可以发送this(当前)对象,因为我只想使用javascript onclick为此吗?

so from the above code what i am trying to do is, when the user clicks on any of the tab all the remaining tabs should be unactive, and the current current element/tab should be active, but the above code is not working, so can anyone please let me know, how to make the above code work, also is there anyway that we can send the this(current) object when the user clicks on the tab, because i want to use only javascript onclick for this ?

推荐答案

使用此html获取被单击的元素:

Use this html to get the clicked element:

<div class="row" style="padding-left:21px;">
    <ul class="nav nav-tabs" style="padding-left:40px;">
        <li class="active filter"><a href="#month" onclick="Data('month', this)">This Month</a></li>
        <li class="filter"><a href="#year" onclick="Data('year', this)">Year</a></li>
        <li class="filter"><a href="#last60" onclick="Data('last60', this)">60 Days</a></li>
        <li class="filter"><a href="#last90" onclick="Data('last90', this)">90 Days</a></li>
    </ul> 
</div>

脚本:

 function Data(string, el)
 {
     $('.filter').removeClass('active');
     $(el).parent().addClass('active');
 } 

这篇关于如何将此元素传递给javascript onclick函数并向该clicked元素添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆