2016-11-11 57 views
0

我有一个包含HTML的变量。环绕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 

所有段落标记已被删除的,而且似乎第一段后停止。有什么我在这里失踪?如果需要,我可以发布更多的代码或解释更多。

在此先感谢。

回答

1

您需要创建一个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>'; 
 

 
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>

+0

神奇这部作品后,您可以通过创建jQuery对象的更新内容!非常感谢。我想我的问题并没有像你提到的那样引用HTML对象引用。几个小时前,我做了这样的事情,但我认为它不起作用,将其删除。无论如何,谢谢! – Pooshonk