jQuery:如何编写选择器以查找以给定子字符串结尾的类的元素? [英] JQuery: how to write a selector to find elements with a class ending with a given substring?

查看:120
本文介绍了jQuery:如何编写选择器以查找以给定子字符串结尾的类的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将JQuery用于我的Web应用程序.我不知道如何为这种情况编写选择器.

I use JQuery for my web application. I don't know how to write a selector for this situation.

<a class="abc def xyz-delete-confirm efg">text</a>

<a class="abc def delete-confirm">text</a>

我需要找到所有以"-delete-confirm"结尾的类或名为"delete-confirm"的类的链接.

I need to find all links that has a class ending with "-delete-confirm" or has a class called "delete-confirm".

我知道如何处理称为删除确认"的类的情况. 删除确认情况"如何?我可以使用一个选择器来涵盖两种情况吗?

I know how to handle the situation of having a class called "delete-confirm". How about the "-delete-confirm situation"? Can I have a single selector covering two situations?

感谢您的任何输入!

致谢.

推荐答案

您可以像这样组合它们.

You can combine them like this.

var $allofthem = $('[class$="-delete-confirm"],.delete-confirm');

请注意,如果类名称出现在某个元素的类列表的末尾,并且仅以-delete-confirm结尾,则该属性值仅以选择器结尾,并且将仅被考虑

Note since this is just an attribute value ends with selector if the class name appears in the end of the list of classes for an element and ends with -delete-confirm will be only considered

使用带结束符的选择器和类选择器的组合.

Use ends-with selector and combination of your class selector.

对于纯选择,您可以执行此操作(与它在classList中出现的位置或有多少个类无关):

For pure selection you can do this (Doesn't matter where it appears in the classList or how many classes it has):

var regExp = /-delete-confirm(\s|$)/; //I am sure regex can be improved

var $allofthem = $('a').filter(function(){
    return regExp.test(this.className) || $(this).is('.delete-confirm');
});

演示

Demo

这篇关于jQuery:如何编写选择器以查找以给定子字符串结尾的类的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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