2010-11-02 42 views
4

我想用新值替換名稱屬性的一部分。該值取決於原始值。 name屬性的數值爲:時隙[timeslot_1] [開始]替換jQuery中表單元素屬性的一部分

  1. 如何增加價值「timeslot_1」到「timeslot_2」,並與這一個替換原來的價值?

  2. cloneElm由兩種類型的元素(輸入和選擇)組成 - 我希望能夠捕獲我的循環中的兩個元素。

的代碼,我到目前爲止有:

$(cloneElm).children('span').children('input').each(function(id) { 
     var newName = $(this).attr('name').replace('timeslot_1', 'timeslot_2'); 
     $(this).attr('name', newName); 
    }); 

感謝

回答

2

其實我不知道我是在正確的軌道上,因爲我是你的問題有點困惑但這是一個刺戳。

$(cloneElm).children('span').children('input').each(function(id) { 
     var mynumber = parseInt((($(this).attr('name')).split("_"))[1]); 
     var newName = $(this).attr('name').replace('timeslot_' + mynumber, 'timeslot_' + (mynumber + 1)); 
     $(this).attr('name', newName); 
    }); 

閱讀一些其他職位,這可能得到清理這樣

$(cloneElm).find(':input').attr('name', function(i, name) { 
    var mynumber = parseInt(name.split("_")[1]); 
    return name.replace('timeslot_' + mynumber, 'timeslot_' + (mynumber + 1)); 
}); 
2

後,我想這與.attr()更通用的方法是你追求的:

$(cloneElm).find(':input').attr('name', function(i, name) { 
    return name.replace('timeslot_1', 'timeslot_2'); 
}); 
0
  • 您可以將函數作爲第二個參數傳遞給attr(),從而消除每個需要()
  • 爲了同時選擇輸入選擇元素,您需要相應地調整選擇器。
  • 最後,您也可以爲replace()方法提供正則表達式和函數。

這裏是結合上述的例子:

$(cloneElm).children('span').children('input, select').attr("name", function() { 
    return this.name.replace(/timeslot_(\d+)/, function ($0, $1) { 
     return "timeslot_" + (+$1 + 1); 
    }); 
}); 
0

更通用的,這只是增加對所有選擇的數量和輸入字段名稱屬性。

$(cloneElm).children('span').children('input, select').attr('name', function(i, name) { 
    if ((var result = name.match(/\d+$/)) && result) 
    return name.replace(/\d+$/,parseInt(result)+1)); 
}); 
0

可能(如許多人所指出的那樣)使用字符串分割和正則表達式來做到這一點,但在我看來這是一種混亂的,可以說是不必要的。

如果您使用jQuery 1.4.3或更高版本,則可以使用HTML5 data屬性將數據存儲在HTML元素中供以後使用[1]。

我會讓你決定如何最好地選擇你所需要的元素,但這樣的事情應該提供您需要的功能:

<script type="text/javascript"> 

function inc_timeslot(elem) { 

    // calculate our next timeslot however we need to 
    var timeslot = $(elem).data("timeslot"); 

    timeslot += 1; 

    // set the attribute 
    $(elem).attr("name", "timeslot_" + timeslot); 

    // and update the data attribute for next time 
    $(elem).data("timeslot", timeslot); 


} 

</script> 

<!-- ... --> 

<input name="timeslot_1" data-timeslot="1"> 
  1. 在早期版本的jQuery,你可以使用jQuery的data函數來設置數據,但這意味着您可能需要使用內嵌script標記。