programing tip

jQuery로 텍스트를 변경하는 방법

itbloger 2020. 11. 13. 07:53
반응형

jQuery로 텍스트를 변경하는 방법


나는이 h1의 ID로 toptitle이 동적으로 생성되고, 나는 HTML을 변경할 수 없습니다입니다. 페이지에 따라 다른 제목이 있습니다. 이제 Profile 일 때 New wordjQuery 로 변경하고 싶습니다 .

<h1 id="toptitle">Profile</h1> // Changing only when it is Profile  
// to
<h1 id="toptitle">New word</h1>

참고 : 텍스트가 Profile이면로 변경하십시오 New word.


다음과 같은 것이 트릭을 수행해야합니다.

$(document).ready(function() {
    $('#toptitle').text(function(i, oldText) {
        return oldText === 'Profil' ? 'New word' : oldText;
    });
});

이 경우 내용 만 대체됩니다 Profil. textjQuery API를 참조하십시오 .


이것은 잘 작동합니다 (사용 .text():

$("#toptitle").text("New word");

이런 식으로 작동합니다.

var text = $('#toptitle').text();
if (text == 'Profil'){
    $('#toptitle').text('New Word');
}

:contains()선택기로도 할 수 있습니다.

$('#toptitle:contains("Profil")').text("New word");

예 : http://jsfiddle.net/niklasvh/xPRzr/


가장 깨끗한

깨끗한 접근을 위해 이것을 시도하십시오.

var $toptitle = $('#toptitle');

if ( $toptitle.text() == 'Profile' ) // No {} brackets necessary if it's just one line.  
  $toptitle.text('New Word');         

$('#toptitle').html('New world');

또는

$('#toptitle').text('New world');

매우 간단합니다.

$(function() {
  $('#toptitle').html('New word');
});

html 함수는 html도 허용하지만 텍스트를 대체하는 것은 간단합니다.

참고 URL : https://stackoverflow.com/questions/6411696/how-to-change-a-text-with-jquery

반응형