[英]How to get portion of the attribute value using jquery
我的属性值为:
<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
的“值”是十六进制值,字符[af]将始终为小写。 它也很容易调整以匹配其他值,例如,如果我将正则表达式更改为/component-([0-9a-f]{2})/
,匹配数组将是["component-3a", "3a"]
。
match方法将正则表达式作为其输入,并在字符串中搜索结果。 结果作为匹配数组返回,第一个索引是完全匹配(对于此,等效的正则表达式将是/Promotion-[0-9a-f]{2}/
)。 任何子表达式(括号中括起的表达式)匹配都按照它们在表达式中出现的顺序添加到数组中,因此表达式的(Promotion)
部分将添加到索引1处的数组中([0-9a-f]{2})
在索引2处添加了([0-9a-f]{2})
。
var id = $("div.promotion").attr("id");
var index = id.indexOf("Promotion");
var promotion = '';
// if the word 'Promotion' is present
if(index !== -1) {
// extract it up to the end of the string
promotion = id.substring(index);
// split it at the hyphen '-', the second offset is the promotion code
alert(promotion.split('-')[1]);
} else {
alert("promotion code not found");
}
你可以得到这样的id属性:
var id= $('div.promotion').attr('id');
但后来我认为你必须使用正则表达式来解析字符串中的数据,格式似乎不是直截了当的。
如果您在id中存储了大量信息,您可以考虑使用多个属性,例如:
<div class="promotion" zone="3a-2f-2f" home="2f"></div>
然后你可以得到这样的数据:
var zone= $('div.promotion').attr('zone');
var home= $('div.promotion').attr('home');
或者你可以使用jQuery.data()
HTH
$(function () {
var promotion = $('.promotion').attr('id').match(/Promotion-([0-9a-f]{2})/);
if (promotion.length > 0) {
alert(promotion[1]);
}
else {
return false;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.