Development Tip

JQuery는 내부 텍스트를 변경하지만 HTML은 유지합니다.

yourdevel 2020. 11. 27. 21:29
반응형

JQuery는 내부 텍스트를 변경하지만 HTML은 유지합니다.


HTML 요소의 텍스트를 변경하고 싶지만 나머지 내부 HTML은 jQuery로 보존하고 싶습니다.

예를 들면 :

<a href="link.html">Some text <img src="image.jpg" /></a> 

"Some text"를 "Other text"로 바꾸면 결과는 다음과 같아야합니다.

<a href="link.html">Other text <img src="image.jpg" /></a> 

편집 : 내 현재 솔루션은 다음과 같습니다.

var aElem = $('a');
var children = aElem.children();

aElem.text("NEW TEXT");
aElem.append(children); 

하지만 좀 더 우아한 방법이 있어야합니다.


이것은 잘 작동하는 것 같습니다.

Live Demo

<html>
    <head>
    </head>
    <body>
        <a href="link.html">Some text <img src="img.jpg" /></a>
    </body>

    </html>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
            var $link = $('a');
            var $img = $link.find('img'); 
            $link.html('New Text');
            $link.append($img);
        });
    </script>

링크를 수정할 수 없기 때문에 옵션은 단순히 사용하는 것입니다. replace

$("a").html($("a").html().replace("Some text", "Other text"));

jsfiddle의.


범위에서 변경하려는 텍스트를 줄 바꿈

<a href="link.html"><span>Some text</span> <img src="image.jpg" /></a> 

$('a span').html( 'new text' );

내 해결책은 조금 늦었지만.

$('a').each(function() {
    var contents = $(this).contents();
    if (contents.length > 0) {
        if (contents.get(0).nodeType == Node.TEXT_NODE) {
            $(this).html('NEW TEXT').append(contents.slice(1));
        }
    }
});

몇 가지 참고 사항 :

  1. contents()와 달리 텍스트 노드를 포함합니다 children().
  2. 를 통해 내용 복사본 을 만들어야합니다. var contents = ...그렇지 않으면 나머지 요소가으로 교체되면 영원히 손실됩니다 $(this).html('NEW TEXT').
  3. length검사는 선택 사항이지만 권장합니다.
  4. nodeType검사는 선택 사항이지만 권장합니다.

다른 방법은 contents()다음과 같이 방법 을 사용하는 것입니다 .

주어진

<a href="link.html">Some text <img src="image.jpg" /></a>

'Some text'jQuery로 바꿀 수 있습니다.

var text = $('a').contents().first()[0].textContent;
$('a').contents().first()[0].textContent = text.replace("Some text", "Other text");

여기에 jsFiddle 예제가 있습니다 .

의 아이디어는 사용자 charlietfl 답변 한이 질문에서 contents()영감을 받았습니다.


.contents ()로 변경할 수 있습니다.

$('.yourElement').contents()[0].data = 'New Data';

귀하의 경우 "[0] .data"는 텍스트 데이터입니다.


이 코드를 시도

$('a').live('click', function(){
    var $img = $(this).find('img'); 
    $(this).text('changed');
    $(this).append($img);
});

내부 요소가 무엇인지 또는 텍스트가 무엇인지 알 필요가없는 효율적이고 강력한 방법 :

var $a = $('a');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

일반 js 기능을 사용하십시오.

$ ( 'a') [0] .firstChild.nodeValue = "새 텍스트";


<span>요소 를 추가하고 해당 요소의 텍스트를 변경해야합니다. 예 :

<a href="link.html"><span id="foo">Some text</span><img src="image.jpg" /></a>

그런 다음 jQuery에서 호출 할 수 있습니다.

$("#foo").html("Other text");

결과는 다음과 같습니다.

<a href="link.html"><span id="foo">Other text</span><img src="image.jpg" /></a>

This is an improvement I've made to the jquery.uniform library. Specifically the $.uniform.update() function. I took the idea from acheong87 and changed it a bit.

The idea is to change the text in a span but preserve the inner HTML and event bindings. No need to store and append HTML this way.

if ($e.is("input[type=button]")) {
    spanTag = $e.closest("span");
    var contents = spanTag.contents();

    if (contents.length) {
        var text = contents.get(0);

        // Modern browsers support Node.TEXT_NODE, IE7 only supports 3
        if (text.nodeType == 3)
            text.nodeValue = $e.val();
    }
}

I added a jQuery function for that need.

you may need to convert the html-entities to text representation, so i added decodeEntities function.

function decodeEntities(encodedString) {
 if (typeof encodedString != "string") return encodedString;
 if (!encodedString) return "";
 var textArea = document.createElement('textarea');
 textArea.innerHTML = encodedString;
 return textArea.value;
}
jQuery.fn.textOnly = function(n) {
  if (this.length > 0)
   $(this).html(decodeEntities($(this).html()).replace($(this).text(), n));
  return $(this);
 }

Usage example $('selector').textOnly('some text')


My generic version:

let button = $('#yourElement');
button.html(button.html().replace(button[0].innerText, "New Text"));

Shorthand for more elements and leading text to change:

elemshtml = '';
$("a *").each(function(){elemshtml +=$(this)[0].outerHTML});
$("a").html('Some text' + elemshtml);

참고URL : https://stackoverflow.com/questions/5232862/jquery-change-inner-text-but-preserve-html

반응형