2016-07-18 2 views
1

나는 내가 만든 웹 API에 아약스 호출에서 얻고 HTML 문자열을 얻고있다검색하고 이미지 태그

배경에서 SRC URL을 변경하기 위해 HTML 문자열을 구문 분석. 그러나 DOM을로드하는 예제를 보았습니다. 문자열로 작업하고 있는데, 제 문제에 대한 정규식, jquery, 하위 문자열 접근 방식이있을 수 있다고 생각합니다.

내가 버튼 액션을 통해 트리거됩니다 미리 정의 된 URL로 변경해야합니다 IMG 태그를 포함하는 HTML 객체를 통해 갈 수있는 능력이 필요합니다

질문. 현재이 문제에 대한 Jquery 접근 방식을 시도하고 있지만 URL을 변경하는 데 문제가 있습니다. html을 문자열로 받고 있는데 ~~/picture~~으로 토큰 화하는 예제 문자열에서 두 개의 다른 img 태그를 포함하는 배열을 갖게 될 것입니다. 이 HTML 문자열을 토큰화할 때부터 정규 표현식이나 부분 문자열 접근법이 더 효율적일까요?

샘플 코드

var newUrl = "http://maps.google.com/mapfiles/kml/shapes/bus.png"; 
var imageTag = contentObject.Content.split("~~/picture~~"); 
     for (var i = 0; i < imageTag.length; i++) { 
      var checkValue = imageTag[i]; // checking the array value for accuracy 
      var testChangeSrc = $(imageTag[i]).attr("src", newUrl); 
     } 

내가 예상 한대로이 코드는 HTML을 변경하지 않는 코드

와 문제. 내가 본 것으로부터 다른 none img 객체를로드 중입니다.

샘플 문자열

<p>~~/Document Text~~When it comes to accounting and advisory services, is the unique firm of choice. As a trusted advisor to our clients, we bring an integrated client service approach with dedicated industry experience. respects the value of every client relationship and provides clients throughout the U.S. with an unwavering commitment to hands-on, personal attention from our partners and senior-level professionals.</p><p>~~/Document Text~~in search of a trusted advisor to deal with their state and local tax needs. Through our leading best practices and experience, our SALT professionals offer quality and ease to the client engagement. We are proud to provide highly comprehensive services.</p><p>~~/picture~~<br></p><p> 
    <img src="/sites/ContentCenter/Graphics/map-al.jpg" alt="map al" style="width&#58;611px;height&#58;262px;" />&#160;~~end~~<br></p><p><br></p><p>~~/picture~~<br></p><p> 
    <img src="/sites/ContentCenter/Graphics/Firm_Telescope_Illustration.jpg" alt="Firm_Telescope_Illustration.jpg" style="margin&#58;5px;width&#58;155px;height&#58;155px;" /> </p><p>~~end~~<br></p><p>~~/Document Heading 1~~Image Test 3<br></p> 
    <img alt="base64 test" /> 
</div><div class="ExternalClassAF0833CB235F437993D7BEE362A1A88A"><br></div><div class="ExternalClassAF0833CB235F437993D7BEE362A1A88A"><br></div><div class="ExternalClassAF0833CB235F437993D7BEE362A1A88A"><br></div> 

IntendedGoal

내 의도 한 목표는 모든 IMG 태그의 SRC의 URL을 변경하는 것입니다. 예제 문자열은 내 컨트롤러에서 제공하는 표준 형식입니다. 이 문자열을 토큰화할 때 부분 문자열 접근 방식을 사용할 것이기 때문에? 또는 정규식?

+2

아니요. 당신은 HTML에 regexes를 사용하지 않는다. 당신은 DOM 파서를 사용한다. –

+0

내 프로젝트를 지연시킬 수없는 작은 조각으로 문자열을 깨고 있기 때문에 나는 그것을 향해 찾고 있었다. –

+0

왜 div에 이미지를 주입하고 그것을 파싱하지 않습니까? 내가 당신의 문제를 해결할 수 있습니다 샘플을 배치 – EasyE

답변

1

이 방법이 가장 쉬운 방법이며 jQuery보다 효율적인 것으로 나타났습니다. 기본적으로 div에 문자열을 주입하고 JavaScript를 사용하여 div에있는 HTML 문자열을 구문 분석합니다. div에 문자열을 배치하면 솔루션에 논리/필터링을 추가하려는 경우 더 많은 기능과 유연성을 제공합니다. 누구나 따라갈 수있는 간단한 코드 블록을 배치하여 솔루션을 수용 할 수 있도록 변경했습니다. 행운을 빌어 요.

function parseHtmlString(yourHtmlString) { 
var element = document.createElement('div'); 
element.innerHTML = yourHtmlString; 
var imgSrcUrls = element.getElementsByTagName("img"); 
for (var i = 0; i < imgSrcUrls.length; i++) { 
     var urlValue = imgSrcUrls[i].getAttribute("src"); 
     if (urlValue) { 
     imgSrcUrls[i].setAttribute("src", "You Desired Change"); 
     } 
    } 
} 
+0

이 Jquery를 통해 그것을 시도 후 이해가 되니 –

+0

U는 객관적인 C에 대한 코드를 제공 할 수 있습니다 Logged – Grigo

관련 문제