2016-07-25 3 views
1

모든 하위 HTML을 변경하지 않고이 span 태그에서 @ 문자를 제거하는 방법을 알려주시겠습니까?.text() 콘텐츠를 변경하고 하위 HTML 유지

$('button').click(function() { 
 
    // ... 
 
});
#name { 
 
    background-color: #ccc 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span> 
 
    <span id="name"> 
 
    <a href="#">Harry</a> 
 
    </span> 
 
    
 
    says: Hello @<span id="name"> 
 
    <a href="#">Hermione</a> 
 
    </span> 
 
</span><br /> 
 

 
<button>Remove</button>

내 생각 : 부모 .text(), 분할 문자 @, 재정의 부모 텍스트 (parent.text(''))를 얻을 부모에게이 개 부분을 추가합니다. 그러나이 방법은 큰 문제가 있습니다. 모든 자식 html은 보관되지 않습니다.

+4

을 제외하고 :: 당신은 복제 할 수 없습니다 ID의 ... ID는 고유해야합니다 – DaniP

+0

http://stackoverflow.com/questions/4106809/how-can-i -change-an-elements-text-changing-its-child-elements – lintu

답변

2

나는 외부에 <span>이라는 ID를 추가했으며 사용자의 이름 ID는 중복 제거했습니다.

+0

답변 : http://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without- 변화하는 자식 요소가 아마도 더 좋다. –

+0

죄송합니다. 제 질문을 확장 할 수 있습니까? 예 : span 태그에 두 개 이상의 문자'@'가 있는데 그 중 하나 (이전 사용자 이름) 만 제거하려고합니다. 어떻게해야합니까? –

+0

질문을 편집하여 확장 된 예를 표시 할 수 있습니다. 또한 사용자 이름 앞에 @와 다른 이름 앞에 @가 어떻게 다른지에 대해서도 설명하십시오. 차이점을 명확하게 설명 할 수 있다면 아마 정규식이있을 것입니다. –

2

$('button').click(function() { 
 

 
    $('#outer').html($('#outer').html().replace(/@/,'')); 
 
    
 
});
#name { 
 
    background-color: #ccc 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span id='outer'><span id="name"><a href="#">Harry</a></span> says: Hello @<span id="name2"><a href="#">Hermione</a></span></span> 
 

 
<br /> 
 

 
<button>Remove</button>

은 첫째로 당신은 클래스 속성을 id 중복을 변경해야합니다, 또는 완전히 제거합니다.

실제 문제를 해결하려면 최상위 레벨 span에있는 노드를 반복하고 모든 textNode 값에 나타나는 @자를 제거하십시오. 이 시도 :

$('button').click(function() { 
 
    $('body > span').contents().each(function() { 
 
    if (this.nodeType == 3) { 
 
     this.nodeValue = this.nodeValue.replace('@', ''); 
 
    } 
 
    }); 
 
});
#name { 
 
    background-color: #ccc 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span> 
 
    <span class="name"> 
 
    <a href="#">Harry</a> 
 
    </span> says: Hello @<span class="name"> 
 
    <a href="#">Hermione</a> 
 
    </span> 
 
</span> 
 
<br /> 
 

 
<button>Remove</button>

+0

감사합니다. 작은 질문 :'this.nodeType'이 3이라는 것을 어떻게 알 수 있습니까? –

+1

다음과 같이 진행됩니다 : https://developer.mozilla.org/en/docs/Web/API/Node/nodeType 'Node.TEXT_NODE'로 '3'을 대체 할 수 있지만 구형 브라우저에서는 지원하지 않을 수 있습니다. –

+0

... 저는'var nodeType = ...;과 같은 것을 찾고 있습니다. if (this.nodeType == nodeType) {}'. 링크 주셔서 감사합니다. –

관련 문제