2016-06-28 4 views
0

다음과 같은 문제가 있습니다. 나는 AJAX를 통해 얻는 특정 문자열을 찾아서 대체하고 싶다.JQuery에서 문자열 찾기 및 바꾸기

코드 :

JQuery와 다음 HTML (예 c88에 대한) 회사 ID에서

if(!countflag) { 
    $('.panel-body > p').each(function() { 
     var content = $(this).find("span").html(); 

     $.ajax({ 
      url: '/vacatures.php', 
      data: {company: content}, 
      type: 'post', 
      success: function(output) { 

       var text = $(this).find("span").text(); 
       $(this).text(text.replace(content, output)); 

      } 
     }); 


     if(content) { 
      countflag = true; 
     } 
    }); 
} 

표시됩니다. 이 사실을 찾아서 회사의 실제 이름으로 대체해야합니다.

ID는 span 태그 안에 있습니다. ID를 찾고 바꿔주는 것이 더 쉬워 질 것이라고 생각했습니다.

AJAX는 .panel-body > p에 표시된 ID에 해당하는 회사 이름을 다시 보내는 vacatures.php으로 전화를 보냅니다.

이 시점에서 나는 회사 이름으로 ID를 찾아서 바꿔야하는 방법을 고집합니다.

UPDATE (HTML 코드 - 부분적으로) :

HTML Code

+0

우리에게 html을 보여주십시오. 페이지에 회사 ID가 여러 개 있습니까? – Esko

+0

네, 여러개 있습니다, 나는 그 코드가 닫힘 때문에 작동하지 않을 수있는 – Chris

답변

1

를 작동하는지 알려 주시기 바랍니다 success callbackeach callbackthis과 다릅니다 ... javascr에서 클로저가 작동하는 방법을 살펴야합니다. IPT : 그런데 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

, 첫 번째 this 참조 저장해야 빠른 수정이하기 위해 : 변수 text이 정의되지 않은 것 같다 :

$('.panel-body > p').each(function() { 
 
    // keep a memory reference of this 
 
    var self = this; 
 
    var item = $(self); 
 
    var content = item.find("span").html(); 
 

 
    $.ajax({ 
 
    url: '/vacatures.php', 
 
    data: {company: content}, 
 
    type: 'post', 
 
    success: function(output) { 
 
     
 
     var text = item.find("span").text(); 
 
     
 
     // the following expression cannot work because text isn't defined 
 
     item.text(text.replace(content, output)); 
 

 
    } 
 
    }); 
 

 
});

노트 ; 일반적으로 코드에는 리팩토링이 필요합니다.

+0

다음과 같은 오류가 발생했습니다 :'잡히지 않은 TypeError : self.find가 함수가 아닙니다' – Chris

+0

'var self = this'를 했습니까? – Hitmands

+0

네, 답안의 모든 내용을 복사했습니다. – Chris

-1

이 당신은 ... 내부 this 폐쇄 문제가있는

if(!countflag) { 
    $('.panel-body > p').each(function() { 
     var content = $(this).find("span").html(); 

     $.ajax({ 
      url: '/vacatures.php', 
      data: {company: content}, 
      type: 'post', 
      success: function(output) { 

       $(this).find("span").html(output) 


      } 
     }); 


     if(content) { 
      countflag = true; 
     } 
    }); 
} 
+0

글을 편집 할 것입니다 ... – Hitmands

+0

그러면 정말 downvoting을 좋아합니까? 방법을 보여주는 대신에 ?? – patilprashant6792

+0

말했듯이, 닫힘 때문에 작동하지 않을 수 있습니다 ... 기본적으로'$ (this) .find ("span") .html (output)'은'this'가 같지 않기 때문에 결과를 생성 할 수 없습니다 'var content = $ (this) .find ("span") .html();'표현식의'this '. 당신이 내 대답을 볼 필요가있는 방식으로. 당신의 대답이 잘못 되었기 때문에 나는 downvoted. – Hitmands

관련 문제