2016-06-28 18 views
0

我遇到以下问题。我想找到并替换我通过AJAX获得的特定字符串。查找并替换JQuery中的字符串

代码:

JQuery的:

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; 
     } 
    }); 
} 

在HTML公司ID(例如c88)被示出。这需要找到并替换为公司的实际名称。

该ID在span标签内。我认为这会更容易找到并替换ID。

AJAX发送呼叫到vacatures.php,该呼叫返回与.panel-body > p中显示的ID相对应的公司名称。

在这一点上我坚持如何成功找到并用公司名称替换​​ID。

UPDATE(HTML代码 - 部分):

HTML Code

+0

请向我们展示html。网页上是否有多个公司ID? – Esko

+0

是的,有多个,我会编辑帖子 – Chris

回答

1

你有一个封闭的问题...里面thissuccess callback不同于each callbackthis ......您需要了解javascr中的闭包工作方式IPT:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

的方式,才能有你需要保存第一this参考快速修复:

$('.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)); 
 

 
    } 
 
    }); 
 

 
});

注意事项:变量text似乎没有定义;通常代码需要重构。

+0

我收到以下错误:'未捕获的TypeError:self.find不是函数' – Chris

+0

你做了'var self = this'吗? – Hitmands

+0

是的,我复制了你的答案 – Chris

-1

请让我知道,如果这个工程

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'。对于一种方式,你需要看看我的答案。我低估了你的回答,因为你的回答是错误的。 – Hitmands