如何检查以结尾的类? [英] How can I check classes that ends with?

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

问题描述

我有一些元素,例如:

<div class="button 17-facebook-dashboard-check">Elem1<div>
<div class="button 18-google-dashboard-check">Elem2<div>
<div class="button 19-twitter-dashboard-check">Elem3<div>
<div class="button">Elem4<div>

和以下处理程序:

$('.button').click(function () { });

在此处理程序中,我需要对具有以-dashboard-check结尾的类的元素执行一些特殊操作,例如外推NN和SOCIAL.

例如,如果我单击Elem4,则什么也不会发生. 如果单击Elem1,则需要打印17和facebook,两者在两个变量中是不同的.

在jquery上执行此操作的快速方法是什么?正则表达式? .Class的结尾吗?

解决方案

假设您可以控制HTML,则最好使用HTML data-属性将此信息嵌入到以下内容中:

<div class="button" data-id="17" data-service="facebook">Elem1</div>
<div class="button" data-id="18" data-service="google">Elem2</div>
<div class="button" data-id="19" data-service="twitter">Elem3</div>
<div class="button">Elem4</div>

现在,编写仅适用于所需元素的选择器非常容易:

$('.button[data-id][data-service]').click(...);

点击也很容易获得所需的信息:

$('.button[data-id][data-service]').click(function() {
    alert($(this).attr("data-id"));           // with jQuery
    alert(this.getAttribute("data-service")); // without jQuery
});

I have some elements such as:

<div class="button 17-facebook-dashboard-check">Elem1<div>
<div class="button 18-google-dashboard-check">Elem2<div>
<div class="button 19-twitter-dashboard-check">Elem3<div>
<div class="button">Elem4<div>

and a handler on:

$('.button').click(function () { });

Inside this handler I need to do some special operations such as extrapolate NN and SOCIAL for the elements that have a class that finishes with -dashboard-check.

For example if I click on Elem4 nothing should happens. If I click on Elem1 I need to print 17 and facebook, both distinct in two variables.

What the fast way to do this on jquery? regex? .HasClass that endswith?

解决方案

Assuming you have control over the HTML, it would be much preferable to use HTML data- attributes to embed this information into:

<div class="button" data-id="17" data-service="facebook">Elem1</div>
<div class="button" data-id="18" data-service="google">Elem2</div>
<div class="button" data-id="19" data-service="twitter">Elem3</div>
<div class="button">Elem4</div>

It's now very easy to write the selector that only works on the elements you want:

$('.button[data-id][data-service]').click(...);

And also very easy to get the information you need on click:

$('.button[data-id][data-service]').click(function() {
    alert($(this).attr("data-id"));           // with jQuery
    alert(this.getAttribute("data-service")); // without jQuery
});

这篇关于如何检查以结尾的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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