如何获得clicked元素的类? [英] How to get the class of the clicked element?

查看:42
本文介绍了如何获得clicked元素的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何获得被单击元素的class值.

I can't figure it out how to get the class value of the clicked element.

使用下面的代码,每次都会得到"node-205" .

.find('> ul')
.tabs(
{
    selectedClass: 'active',
    select: function (event, ui) {
        //shows only the first element of list
        $(this).children('li').attr('class');
    },
    cookie: { expires: 0 },
    fx: fx
})

HTML:

<ul class="tabs">
  <li class="node-205"></li>
  <li class="node-150"></li>
  <li class="node-160"></li>
</ul>

推荐答案

下面是一个快速的jQuery示例,该示例将click事件添加到每个"li"标记中,然后检索clicked元素的class属性.希望对您有所帮助.

Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

$("li").click(function() {
   var myClass = $(this).attr("class");
   alert(myClass);
});

同样,您不必在jQuery中包装对象:

Equally, you don't have to wrap the object in jQuery:

$("li").click(function() {
   var myClass = this.className;
   alert(myClass);
});

在更新的浏览器中,您可以获取完整的类列表名称:

And in newer browsers you can get the full list of class names:

$("li").click(function() {
   var myClasses = this.classList;
   alert(myClasses.length + " " + myClasses[0]);
});

您可以使用myClass.split(/\s+/);

这篇关于如何获得clicked元素的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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