1. 程式人生 > 實用技巧 >JS中的替換,以及替換指定位置的字串

JS中的替換,以及替換指定位置的字串

批量修改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)

在php生成頁面的時候,就確定每個tihao的替換位置