2013-04-24 17 views
2

我需要修改div,span,select和其他元素的多個ID,類和名稱。jquery使用正則表達式更改多個ID

我會克隆,從最後一排,我有一個表中的HTML,像

var num  = $('.clonedLighting').length; // num of current rows 
var newNum = new Number(num + 1);  // the numeric ID of the new input field being added 

// create the new element via clone(), and manipulate it's ID using newNum value 
var newElem = $('#inputlighting' + num).clone().prop('id', 'inputlighting' + newNum); 

然後在下一步我修改克隆的ID,如

newElem.children('td').children('label.prod_item').prop('for', 'appliancetextfield' + newNum); 
newElem.children('td').children('select.prod_item').prop('id', 'appliancetextfield' + newNum).prop('name', 'appliancetextfield' + newNum).prop('value', ''); 

這是工作確定。然而,appliancetextfield部分現在有更多的元素。我想與

'appliancetextfield'+newNum 

更換包含所有名稱,類別和標識

'appliancetextfield'+num 

,而不是做它的每一個元素。這可能嗎?怎麼樣?

澄清:的ID,類或名字看起來像

appliancetextfield4 
appliancetextfield4_title 
appliancetextfield4_titleText 
appliancetextfield4_msdd 

,並應在這一點上,它看起來像數將永遠只能是個位數變成

appliancetextfield5 
appliancetextfield5_title 
appliancetextfield5_titleText 
appliancetextfield5_msdd 

,但有一天可能要上升到10或更高。感謝您的任何意見。

編輯: 試圖執行谷歌搜索的以下建議和很多: 我現在有:

var num  = $('.clonedLighting').length; // current rows 
var newNum = new Number(num + 1); 

$('#inputlighting' + num).clone().prop('id', function(index, id) { 
    return id.replace(/(appliance.*)\d\d?(.*)/g, "$1" + newNum + "$2"); 
}).insertAfter($('#inputlighting' + num)); 

它看起來像在正確的軌道,但正則表達式和/或背引用不工作。

+0

:爲什麼不只是在一個循環中改變元素('newElem')id,根據頁面中沒有克隆的元素,或者甚至可以使用'.each()'。 – dreamweiver 2013-04-24 06:01:20

+0

我試過了'var val = newElem.html(); val = val.replace(/'appliancetextfield'+ num/g,'appliancetextfield'+ newNum);'但是沒有用。不知道如何使用'each()',因爲不是每個元素都需要修改。 – rotezecke 2013-04-24 06:20:25

+0

不,不,你做錯了,你使用基本的字符串操作函數,你應該使用'.attr()'來改變元素的** id **。 – dreamweiver 2013-04-24 06:32:48

回答

0

我想我明白了:

 //newElem is the newly cloned object 
    newElem.find('[id^=appliance]').prop('id', function(index, id) { 
      return id.replace(/(appliance.*)\d\d?(.*)/g,"$1" +newNum+ "$2"); 
    }); 
    newElem.find('[for^=appliance]').prop('for', function(index, id) { 
      return id.replace(/(appliance.*)\d\d?(.*)/g,"$1" +newNum+ "$2"); 
    }); 
    newElem.find('[name^=appliance]').prop('name', function(index, id) { 
      return id.replace(/(appliance.*)\d\d?(.*)/g,"$1" +newNum+ "$2"); 
    }); 

感謝您的幫助。