我的属性值为:
<div id = "2fComponents-2fPromotion-2f" class = "promotion">
现在我只想获取它的一部分,比如 Promotion
及其值 2f
,我如何使用 jquery 获取它?我们有内置函数吗?
最佳答案
你可以在这里使用正则表达式:
var attId = $(".promotion").attr("id");
// Perform a match on "Promotion-" followed by 2 characters in the range [0-9a-f]
var match = attId.match(/Promotion-([0-9a-f]{2})/);
alert(match[1]); // match[0] contains "Promotion-2f", match[1] contains "2f"
这里假设 Promotion
的“值”是一个十六进制值,字符 [a-f] 总是小写。它也很容易调整以匹配其他值,例如,如果我将正则表达式更改为 /component-([0-9a-f]{2})/
,则匹配数组将为 ["component-3a", "3a"]
.
match 方法将正则表达式作为其输入并在字符串中搜索结果。结果以匹配数组的形式返回,第一个索引是完整匹配项(等效正则表达式仅为 /Promotion-[0-9a-f]{2}/
)。任何子表达式(括在括号中的表达式)匹配项都按照它们在表达式中出现的顺序添加到数组中,因此表达式的 (Promotion)
部分添加到索引 1 处的数组中,并且([0-9a-f]{2})
添加到索引 2。
关于javascript - 如何使用jquery获取属性值的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2772706/