循环HTML变量并将span替换为content
Loop around HTML variable and replace spans with content
我有一个包含HTML的变量。
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';
我试图循环所有的元素,并替换为跨度特定的日期。因此,任何具有variable-source
类的跨度都需要替换为特定的日期,input-source
也是如此。
我已经尝试使用以下命令:
$('span', html).replaceWith(function () {
var id = $(this).attr('id');
// this returns the correct id
//calculations go here
var value = 'testing';
return value
});
输出如下:
testing This is a variable
所有的段落标签都被删除了,似乎在第一段之后就停止了。我是不是漏掉了什么?如果需要,我可以发布更多代码或解释更多。
您需要创建一个html对象引用,否则您将无法获得对更新内容的引用。然后在执行替换操作后从创建的jQuery对象中获取更新内容
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
'<p>Testing</p>';
var $html = $('<div></div>', {
html: html
});
$html.find('span.variable-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced variable for: ' + id;
return value
});
$html.find('span.input-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced input for: ' + id;
return value
});
var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
相关文章:
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- 我如何找到一个句子中的所有空格并替换忽略它们
- 如何用更合适的内容替换document.write
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 用空格替换下划线PHP
- str.split(someString).join(someOtherString)是否等效于替换
- 使用javascript的图像替换循环
- window.location替换并传递URL历史记录条目中的变量
- 替换标记中的属性
- 指令的模板必须只有一个根元素:With restrict E&替换true
- AngularJs对ng消息的自定义替换
- 用超链接替换URLS
- 用cdata标记替换脚本标记
- 在jQuery中将所有
content 替换为 - content
- 使用 Selenium 单击由 Content(内容)隐藏的链接替换为 Selenium XPath
- 循环HTML变量并将span替换为content
- 用.html(content)替换页面内容不工作
- Javascript在不更改子元素HTML和Content的情况下替换标记中的文本
- 在modal中加载iframe时,. mode -content被替换