简体   繁体   English

jQuery如何查找具有特定操作的元素的类

[英]jQuery how to find class of an element which has a particular action

Hi I need to find the class of an element which matches a particular pattern. 嗨,我需要找到与特定模式匹配的元素的类。 Basically what I am trying to do is add custom text to the end of form in a framework based product. 基本上,我想做的是在基于框架的产品中将自定义文本添加到表单末尾。

All instances of the product have the same 产品的所有实例都具有相同的

<form action="/cart" method="post" class="...">
</form>

I need to find the class of the form element in each such instance so that I can traverse to the last child and add my piece of text. 我需要在每个这样的实例中找到form元素的类,以便可以遍历最后一个孩子并添加我的文本。 Is it possible using jQuery alone? 可以单独使用jQuery吗? Thanks 谢谢

Using jquery you can find any element by an attribute by wrapping it with [] 使用jquery,您可以使用[]将属性包装起来,从而按属性查找任何元素

$('[action="/cart"]')

This is where the attribute equals the value, but you can do contains by adding * before the = like so: 这是属性等于值的地方,但是您可以通过在=之前添加*来包含内容,如下所示:

$('[action*=cart]')

Here's a list of attribute selectors: 这是属性选择器的列表:

https://api.jquery.com/category/selectors/attribute-selectors/ https://api.jquery.com/category/selectors/attribute-selectors/

Then get the attribute for class: 然后获取类的属性:

$('[action="/cart"]').attr('class')

Quick sample here: 快速样本在这里:

https://jsfiddle.net/op7bv8Lu/ https://jsfiddle.net/op7bv8Lu/


If you want to get the last element you can add :last to the selector. 如果要获取最后一个元素,可以将:last添加到选择器。

$('[action*=cart]:last').attr('class')

Again, sample here: 再次,在这里采样:

https://jsfiddle.net/xzpag6up/ https://jsfiddle.net/xzpag6up/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM