在ID名称中查找匹配并分配给标题标记

时间:2013-10-16 14:47:42

标签: jquery

我在页面上有一个网格,它有一系列动态生成的单选按钮。所有单选按钮都有一个类似的ID名称,除了位于ID名称的中间 - 增量变量CTL ##(ctl00,ctl01等)

<input id="ctl00_PageBody_grdCustomer_ctl01_rdoCustomerSelect" type="radio" value="rdoCustomerSelect">
<input id="ctl00_PageBody_grdCustomer_ctl02_rdoCustomerSelect" type="radio" value="rdoCustomerSelect">
<input id="ctl00_PageBody_grdCustomer_ctl03_rdoCustomerSelect" type="radio" value="rdoCustomerSelect">
<input id="ctl00_PageBody_grdCustomer_ctl04_rdoCustomerSelect" type="radio" value="rdoCustomerSelect">
<input id="ctl00_PageBody_grdCustomer_ctl05_rdoCustomerSelect" type="radio" value="rdoCustomerSelect">

我发现代码与ID匹配,如果它以特定模式开头/结尾,但无法弄清楚如何提取匹配模式并将其分配给属性。

我的最终目标是将标签格式化如下......

<input id="ctl00_PageBody_grdCustomer_ctl01_rdoCustomerSelect" type="radio" value="rdoCustomerSelect" title="rdo_ctl01">
<input id="ctl00_PageBody_grdCustomer_ctl02_rdoCustomerSelect" type="radio" value="rdoCustomerSelect" title="rdo_ctl02">
<input id="ctl00_PageBody_grdCustomer_ctl03_rdoCustomerSelect" type="radio" value="rdoCustomerSelect" title="rdo_ctl03">

等等......

有什么建议吗?感谢。

2 个答案:

答案 0 :(得分:1)

尝试:

$('input').attr('title', function () {
    var matches = $(this).attr('id').match(/ctl00_PageBody_grdCustomer_(.*)_rdoApplicantSelect/);
    return 'rdo_' + matches[1];
});

<强> jsFiddle example

这会产生:

<input id="ctl00_PageBody_grdCustomer_ctl01_rdoApplicantSelect" type="radio" value="rdoApplicantSelect" title="rdo_ctl01">
<input id="ctl00_PageBody_grdCustomer_ctl02_rdoApplicantSelect" type="radio" value="rdoApplicantSelect" title="rdo_ctl02">
<input id="ctl00_PageBody_grdCustomer_ctl03_rdoApplicantSelect" type="radio" value="rdoApplicantSelect" title="rdo_ctl03">
<input id="ctl00_PageBody_grdCustomer_ctl04_rdoApplicantSelect" type="radio" value="rdoApplicantSelect" title="rdo_ctl04">
<input id="ctl00_PageBody_grdCustomer_ctl05_rdoApplicantSelect" type="radio" value="rdoApplicantSelect" title="rdo_ctl05">

答案 1 :(得分:0)

您可以使用split()

$('input').attr('title', function() {
    return 'rdo_' + this.id.split('_')[3]; 
});

Here's a fiddle