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