JQuery 替换字符串中的元素
JQuery replace elements within string
我有一个包含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);
});
相关文章:
- 对id以某个字符串开头的元素进行计数
- 如何使用jQuery each分离字符串中的元素
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 数组中元素(字符串)的总和
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 从同级字符串中指定最接近的元素类
- 获取类中包含给定字符串的元素的ID
- 在元素列表中搜索给定字符串
- 转换<a>使用jQuery将文本字符串转换为dom元素
- 为什么不是't my元素:使用变量而不是字符串时包含(变量)功?jquery
- 无法从量角器测试中元素的值返回字符串
- 从字符串创建dom元素时添加多个类
- 在javascript中将字符串转换为Node元素
- 用HTML元素替换字符串的一部分
- Javascript选择元素到字符串的比较
- 如何比较两个字符串并删除jquery中的元素
- 按名称获取元素字符串
- 如何确定光标在表单元素字符串中的位置
- 获取react元素字符串类型
- 为什么可以'我是否在JavaScript中设置数组元素(字符串)的属性