JS中的替換,以及替換指定位置的字串
阿新 • • 發佈:2020-06-27
批量修改name屬性中的值
// 渲染完成,開始修改ansewer的name屬性 $('.sub_timu_zong_tihao').each(function(i){ $(this).find('input[name*=bianhao]').each(function(){ // 首先獲取name的值,對 console.log('正在修改bianhao') var old=$(this).attr('name') var now=old.replace('bianhao',i) $(this).attr('name',now) }) })
修改題目的編號
function shuaxin_tihao(){ // 渲染完成,開始修改name中的tihao $('.sub_timu_zong_tihao').each(function(i){ $(this).find('input[name*=tihao]').each(function(){ // 首先獲取name的值,對 console.log('正在修改input中的tihao') var old=$(this).attr('name') var now=old.replace('tihao',i) $(this).attr('name',now) }) $(this).find('textarea[name*=tihao]').each(function(){ // 首先獲取name的值,對 console.log('正在修改textarea中的tihao') var old=$(this).attr('name') var now=old.replace('tihao',i) $(this).attr('name',now) }) $(this).find('*[id*=tihao]').each(function(){ // 首先獲取name的值,對 console.log('正在修改id中的tihao') var old=$(this).attr('id') var now=old.replace('tihao',i) $(this).attr('id',now) }) }) }
由於第一次是根據名字進行替換,這次進行替換,已經沒有名字了。所以,這時候,根據位置去替換
根據位置替換字元
//str:原始字串,index,開始位置,changeStr,改變後的字 function changeStr(str,index,changeStr){ return str.substr(0, index) + changeStr+ str.substr(index + changeStr.length); } //記住的,傳值的時候,第三個要傳字串 var str="row[answer5][tihao]" var a=changeStr(str,13,'1') console.log(a)