jquery를 사용하여 div 내부의 텍스트만 바꿉니다.
나는 다음과 같은 디바가 있습니다.
<div id="one">
<div class="first"></div>
"Hi I am text"
<div class="second"></div>
<div class="third"></div>
</div>
jquery를 사용하여 텍스트만 "Hi I am text"에서 "Hi I am replace"로 변경하려고 합니다.이것은 쉬울지 모르지만 나는 그것을 할 수 없습니다.
사용.$('#one').text('')전부를 비워놓기만 합니다.#One디브
텍스트가 알아서는 안 됩니다.A에 집어넣습니다.span요소.
다음 항목으로 변경:
<div id="one">
<div class="first"></div>
<span>"Hi I am text"</span>
<div class="second"></div>
<div class="third"></div>
</div>
$('#one span').text('Hi I am replace');
텍스트 노드 찾기 (nodeType==3) 및 교체합니다.textContent:
$('#one').contents().filter(function() {
return this.nodeType == 3
}).each(function(){
this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
문서에 따라 하드 코딩된 파일을 교체할 수 있습니다.3위와 같이Node.TEXT_NODE당신이 하는 일이 훨씬 더 분명해요
$('#one').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).each(function(){
this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">
<div class="first"></div>
"Hi I am text"
<div class="second"></div>
<div class="third"></div>
</div>
텍스트를 빈 문자열이 아닌 다른 문자열로 설정해야 합니다.또한 .html() 함수는 div의 HTML 구조를 유지하면서 해야 합니다.
$('#one').html($('#one').html().replace('text','replace'));
바꿀 텍스트를 실제로 알고 있다면 사용할 수 있습니다.
$('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"';
아니면
$('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"';
$('#one').contents(':not(*)')이 경우 텍스트 노드가 아닌 element 자식 노드를 선택하고 두 번째 노드가 대체할 노드입니다.
HTML을 변경할 수 없는 경우를 대비하여 매우 원시적이지만 짧고 효과적입니다. (부모 디브를 비우므로 자식 디브는 제거됩니다.)
$('#one').text('Hi I am replace');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one">
<div class="first"></div>
"Hi I am text"
<div class="second"></div>
<div class="third"></div>
</div>
다른 접근 방식은 요소를 유지하고 텍스트를 변경한 다음 요소를 다시 추가하는 것입니다.
const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)
저도 같은 문제가 있었지만, 텍스트는 상위 요소 안의 첫 번째 노드였습니다.이 경우 이와 같은 작업을 수행할 수 있으며 매우 빠릅니다.
// find the children elements
termsChildren = $('#one').children()
// replace the text, then re-append the children element.
$('#one').text(' "Hi I am replace" ').append(termsChildren)
그렇지 않으면 텍스트 앞으로 이동해야 하는 하위 항목과 그 뒤에 다음 항목을 지정해야 합니다.
// find the children elements
termsChildren = $('#one').children()
// remove all the content
$('#one').text(' ')
// append the first child element
$('#one').append(termsChildren[0])
// add the new text and then the other children
$('#one').text(' "Hi I am replace" ').append(termsChildren.slice(1))
요소의 일반 텍스트를 jQuery로 바꿀 때는 일반 텍스트를 자체적으로 넣을 수 없습니다. 그렇지 않으면 요소 전체를 지우고/또는 바꿉니다.당신은 모든 평문을 a 안에 넣어야 합니다.<span>요소:
$(document).ready(function() {
$("#change-btn").click(function() {
$("#one").children("span").text("Hi I am replace");
});
});
<!-- Import CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- Import JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
<div class="m-2">
<div id="one">
<div class="first"></div>
<span>Hi I am text</span>
<div class="second"></div>
<div class="third"></div>
</div>
<button type="button" class="btn btn-primary btn-sm mt-2" id="change-btn">Click to change text</button>
</div>
언급URL : https://stackoverflow.com/questions/11867269/replace-only-text-inside-a-div-using-jquery
'programing' 카테고리의 다른 글
| 실행된 SQL이 값을 반환하더라도 최대 절전 모드가 null 목록을 반환합니다. (0) | 2023.10.11 |
|---|---|
| ORA-01031 보기를 생성하는 동안 권한이 부족합니까? (0) | 2023.10.06 |
| IFTTT에 대한 입력으로 XML 파일을 RSS 피드에 긁습니다. (0) | 2023.10.06 |
| "tests' module을 잘못 가져옴"은 무엇을 의미합니까? (0) | 2023.10.06 |
| 런타임 오류: 예외를 만들지 못했습니다. (0) | 2023.10.06 |