2013-05-24 2 views
0

텍스트 블록 내에서 태그 위치를 가져올 수 있습니까? 예를 들어 나는 거대한 p 태그를 가지고 있고 그 안에는 많은 텍스트가 있습니다. 사용자는 span 태그 묶음을 p 태그에 동적으로 삽입하는 도구를 갖게됩니다. 어느 시점에서 사용자는 끝나고 내가 한 일을 저장하려고합니다. 제한 사항으로 인해 p 태그의 전체 내용을 저장할 수 없으며 각 개별 범위를 얻어야합니다. 사용자 상호 작용텍스트 블록에서 요소 인덱스 가져 오기

<p>Sam wanted a dog. 
    "If you're <span>a good boy,"</span> said his father. 
    "When you can take care of it yourself" said his mother. 
    Sam cleaned up his <span>room. He ate</span> carrots and broccoli. He stopped making monster noises 
    at night to scare Molly, his older sister. He hung up his cap after baseball practice. 
</p> 

초기 텍스트

<p>Sam wanted a dog. 
    "If you're a good boy," said his father. 
    "When you can take care of it yourself" said his mother. 
    Sam cleaned up his room. He ate carrots and broccoli. He stopped making monster noises 
    at night to scare Molly, his older sister. He hung up his cap after baseball practice. 
</p> 

나는 내가 무엇을 찾고 있어요 것은 스팬 시작을 수행하고 그 곳을 종료 않는 범위 것 같다. 지금까지 내가 할 수 있었던 것은 단지 내용을 반복하는 것이지만 거기에서 어디로 가야할지를 알아 내는데 막혔습니다. 저장해야하는 이유는 사용자가 콘텐츠를 떠나는 방식으로 콘텐츠로 돌아 가기를 기대하기 때문입니다. 따라서 솔루션에서 가져온 위치 태그를 다시 고려해야합니다. 내가

$("p").each(function (index) { 
    $(this).find("span").each(function() { 
      console.log(this); 
    }); 
}); 

내 실제 환경의 시작 얼마나의

샘플 JS는 더 복잡하지만 난 솔루션을 좁힐 기초로 단순화했다. 어떤 도움이나 제안이라도 대단히 감사합니다.

답변

2

.contents method을 사용하면 텍스트 노드를 포함하여 단락의 모든 하위 노드를 가져올 수 있습니다. 이제 할 수있는 그들에 쉽게 루프 :

var ranges = [], 
    i = 0; 
$("thatp").contents().each(function() { 
    var $this = $(this); 
    if (this.nodeType == 1 && $this.is("span")) 
     ranges.push([i, i+=$this.text().length]); 
    else 
     i+=$this.text().length; 
}); 
// result: 
> ranges 
[[31,43],[141,153]] // at least in my console test, you might have different whitespaces 
2

여기 고려하는 함수의 위치를 ​​span의 시작과 끝. 순수한 자바 스크립트 사용.

function getSpanRanges(myP) { 
    var start = -1, result = [], parts = [], partsTypes = []; 
    for (var i = 0; i < myP.childNodes.length; i++) { 
     parts[i] = myP.childNodes[i].outerHTML || myP.childNodes[i].nodeValue; 
     partsTypes[i] = myP.childNodes[i].nodeName; 
     if ("SPAN" == myP.childNodes[i].nodeName) { result.push([start + 1, start + parts[i].length]); } 
     start += parts[i].length; 
    } 
    return result; 
} 

사용 예제 :

var myP = document.getElementsByTagName("p")[0]; 
var spanRanges = getSpanRanges(myP); // this is the ranges array 

See EXAMPLE DEMO here.

당신은 그들이에서 촬영 한 스팬 태그를 다시 넣어 고려해야하는 솔루션을 필요로하기 때문에,이 함수는 위의 세 가지 출력이 있습니다 요소

  • 배열 :

    ["Sam wanted a dog. \"If you're ", "<span>a good boy,\"</span>", " said his father. \"When you can take care of it yourself\" said his mother. Sam cleaned up his ", "<span>room. He ate</span>", " carrots and broccoli. He stopped making monster n…ster. He hung up his cap after baseball practice."] 
    
    을 해당 유형의
  • 배열 :

    ["#text", "SPAN", "#text", "SPAN", "#text"] 
    
  • 그들의 범위 (시작, 종료) 된 배열 :

    [[29, 53], [148, 172]] 
    
관련 문제