JQuery 替换字符串中的元素

JQuery replace elements within string

本文关键字:元素 字符串 替换 JQuery      更新时间:2023-09-26

我有一个包含HTML数据的字符串,例如:

<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, "");
});

接下来,您可以看到两个输入元素的 id 均为 dateInput。我现在需要做的是更改此值,使其是唯一的,使用类似递增的数字。因此,第一个输入应该有 dateInput1 和第二个 dateInput2。

我怎样才能做到这一点?如果可能,最好更改标签中的 for 值以匹配 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/

您可以使用 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);
});

最终,您可以循环访问元素属性以删除以"data-"开头的每个属性。

你应该循环每个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);
});

使用 .index() 获取每个循环中的唯一编号:

$("#content").find(".form-group").each(function() {
    // other code
     $(this).find('input[type="text"])
                 .attr('id', this.id+$(this).index()+1);
 });