[javascript] jQuery를 사용하여 한 태그를 다른 태그로 바꾸기

골:

jQuery를 사용하여 다음 항목을 모두 바꾸려고합니다.

<code> ... </code>

와:

<pre> ... </pre>

내 솔루션 :

나는 다음과 같은 것을 얻었습니다.

$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );

내 솔루션의 문제 :

그러나 문제는 (두 번째, 세 번째, 네 번째 등) “code”태그 사이의 모든 것을 첫 번째 “code”태그 사이의 콘텐츠로 대체한다는 것 입니다.

예 :

<code> A </code>
<code> B </code>
<code> C </code>

된다

<pre> A </pre>
<pre> A </pre>
<pre> A </pre>

나는 “this”와 어떤 종류의 기능을 사용해야한다고 생각하지만, 나는 아직도 배우고 있고, 해결책을 모으는 방법을 정말로 이해하지 못하는 것이 두렵다.



답변

.replaceWith [문서]에 함수를 전달할 수 있습니다 .

$('code').replaceWith(function(){
    return $("<pre />", {html: $(this).html()});
});

함수 내에서 this현재 처리 된 code요소를 참조합니다.

데모

업데이트 : 없습니다 더 큰 성능 차이가 있지만, 경우에 code요소들을 더 정확하기 느낌 직렬화하는 대신 자녀를 추가, 다른 HTML의 자녀가 :

$('code').replaceWith(function(){
    return $("<pre />").append($(this).contents());
});


답변

이것은 훨씬 더 좋습니다.

$('code').contents().unwrap().wrap('<pre/>');

물론 Felix Kling의 솔루션 은 약 2 배 빠릅니다 .


답변

항상 첫 번째 code콘텐츠를 얻는 것이 맞습니다.$('code').html()사용하는 곳마다 항상 첫 번째 요소를 참조하기 항상 습니다.

대신 .each을 사용하여 모든 요소를 ​​반복하고 각 요소를 개별적으로 변경할 수 있습니다 .

$('code').each(function() {
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
    // this function is executed for all 'code' elements, and
    // 'this' refers to one element from the set of all 'code'
    // elements each time it is called.
});


답변

이 시도:

$('code').each(function(){

    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );

});

http://jsfiddle.net/mTGhV/


답변

이건 어때요?

$('code').each(function () {
    $(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});


답변

Felix의 대답을 바탕으로합니다.

$('code').replaceWith(function() {
    var replacement = $('<pre>').html($(this).html());
    for (var i = 0; i < this.attributes.length; i++) {
        replacement.attr(this.attributes[i].name, this.attributes[i].value);
    }
    return replacement;
});

그러면 code대체 pre태그 의 태그 속성이 재현됩니다 .

편집 : 이것은 다른 태그 code안에 있는 태그 도 대체 합니다.innerHTMLcode

function replace(thisWith, that) {
    $(thisWith).replaceWith(function() {
        var replacement = $('<' + that + '>').html($(this).html());
        for (var i = 0; i < this.attributes.length; i++) {
            replacement.attr(this.attributes[i].name, this.attributes[i].value);
        }
        return replacement;
    });
    if ($(thisWith).length>0) {
        replace(thisWith, that);
    }
}

replace('code','pre');


답변

jQuery 1.4.2부터 :

$('code').replaceWith(function(i,html) {
  return $('<pre />').html(html);
});​

그런 다음 새 요소를 선택할 수 있습니다.

$('pre').css('color','red');

출처 : http://api.jquery.com/replaceWith/#comment-45493689

jsFiddle : http://jsfiddle.net/k2swf/16/