2016-01-25 121 views
0

中的元素我有一個包含HTML數據,例如一個字符串:JQuery的替換字符串

<div data-type="date" class="form-group"> 
    <label class="control-label col-sm-5" for="dateInput">Date Input:</label> 
    <div class="col-sm-3"> 
     <input type="text" name="dateInput[]" class="form-control date_picker" id="dateInput"> 
    </div> 
</div> 

<div data-type="date" class="form-group"> 
    <label class="control-label col-sm-5" for="dateInput">Date Input:</label> 
    <div class="col-sm-3"> 
     <input type="text" name="dateInput[]" class="form-control date_picker" id="dateInput"> 
    </div> 
</div> 

我問這個問題,假設我是用DOM工作之前。但是,這只是一個字符串。我做的第一件事是去除從字符串數據屬性:

$("#content").find(".form-group").each(function() { 
    var html = $(this).attr('class', 'form-group')[0].outerHTML.replace(/ data-(.+)="(.+)"/g, ""); 
}); 

接下來,你可以看到,無論是輸入元件具有dateInput的ID。我現在需要做的是改變這個值,使它是唯一的,使用像增加數字的東西。所以,第一個輸入應該有dateInput1和第二個dateInput2。

我該如何做到這一點?如果可能的話,改變標籤中的值以匹配id也是很好的。

感謝

更新

如果我做的:

$("#content").find(".form-group").each(function() { 
     var html = $(this).attr('class', 'form-group')[0].outerHTML.replace(/ data-(.+)="(.+)"/g, ""); 
     $(this).find('input[type="text"]').attr('id', this.id+$(this).index()+1); 

     dataArray.push(html); 
    }); 

它似乎並沒有更新。我這裏有一個例子小提琴https://jsfiddle.net/mLgrfzaL/4/

回答

0

您可以使用jQuery的,以瀏覽它作爲DOM樹評估字符串:

var string = "<div><span>Hello</span></div>"; 
var $parsedDom = $(string); 
$parsedDom.children(); // => <span>Hello</span> 

在你的情況下,如果要應用它,我不清楚它。

回答您的其他問題:

$("#content").find(".form-group").each(function(index) { 

    //$(this).attr('class', 'form-group') has no effect: 
    // you have already found the nodes with this class 

    // removing the "data-" (why?) 
    $(this).removeAttr("data-type"); 

    //modifing the id 
    var $thisInput = $(this).find('input'); 
    var oldId = $thisInput.attr('id'); 
    $thisInput.attr('id', oldId + index); 
}); 

最終,你可以loop on element attribute去除開始「數據 - 」每一個屬性。

0

您應該循環每個input,其中id等於dateInput,然後附加到其舊值index + 1(因爲它是從零開始的)。

$("input[id='dateInput']").each(function(index, value) { 
    var old_id = $(value).attr("id"); 
    var new_id = old_id + (index + 1); 
    $(value).attr("id", new_id); 
}); 
0

使用.index()獲得在每個循環的唯一編號:

$("#content").find(".form-group").each(function() { 
    // other code 

    $(this).find('input[type="text"]) 
       .attr('id', this.id+$(this).index()+1); 

}); 
+0

感謝。我已經做了更新,顯示了我的問題,並與小提琴相關聯 –