2016-11-11 8 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

関連する問題