【问题标题】:jQuery/Javascript: More complex Searching and Replacing in an HTML documentjQuery/Javascript:在 HTML 文档中更复杂的搜索和替换
【发布时间】:2012-07-01 19:20:12
【问题描述】:

我以前在 jQuery 和 Javascript 方面做过一些事情,但不幸的是我不是专家。我找不到任何关于如何使用尽可能少的资源来完成任务的提示。你们也许可以帮帮我:

这是我想做的:

我想找到(使用正则表达式)页面上所有类似 BB 代码的元素,如下所示:

[此处的索引=参数随机数据]

然后我想用我从 ajax 调用收到的内容替换它们,如下所示:

call.php?ndex=here=参数随机数据

或我从相应的 [ndex] 标记中获取的任何参数。

到目前为止,这是我的解决方案/思考过程:

$(document).ready(function() {
    var pattern = /\[ndex\s+(.*?)\]/mg;
    var documentText = $(document.body).text();
    var matches = documentText.match(pattern);

    $('*').each(function () { 
        var searchText = this;
        if ($(searchText).children().length == 0) { 
            $.each(matches, function() {
                //here is where I would need to check for a match and make a call 
                }
            }); 
        } 
    });
});

我真的不知道如何从这里开始工作。我的草图看起来非常笨重和复杂。必须有一个更优雅、更直接的解决方案。

非常感谢你们的帮助。 :)

【问题讨论】:

  • 我不确定这是实现您想要的方式。您应该替换文本服务器端,而不是通过 ajax 调用
  • 感谢您的回复。我需要进行 ajax 调用,因为有替换的文档不一定在带有 php 的服务器上运行。

标签: javascript jquery ajax regex replace


【解决方案1】:

我会做这样的事情:

function ndex_treat(n) {
  // If element is ELEMENT_NODE
  if(n.nodeType==1)
  {
    // If element node has child, we pass them to function ndex_treat
    if(n.hasChildNodes())
      for(var i= 0; i<n.childNodes.length; i++)
        ndex_treat(n.childNodes[i]);
  }
  // If element is TEXT_NODE we replace [ndex ...]
  else if(n.nodeType==3)
  {
    var matches, elemNdex, elemText;
    // While there is one
    while(/\[ndex\s+(.*?)\]/m.test(n.nodeValue))
    {
      // Taking what's before (matches[1]), the "attribute" (matches[2]) and what's after (matches[3])
      matches= n.nodeValue.match(/^([\s\S]*?)\[ndex\s+(.*?)\]([\s\S]*)$/m)
      // Creating a node <span class="ndex-to-replace" title="..."></span> and inserting it before current text node element
      elemNdex= document.createElement("span");
      elemNdex.className= 'ndex-to-replace';
      elemNdex.title= matches[2];
      n.parentNode.insertBefore(elemNdex, n);
      // If there was text before [ndex ...] we add it as a node before
      if(matches[1]!=="")
      {
        elemText = document.createTextNode(matches[1]);
        elemNdex.parentNode.insertBefore(elemText, elemNdex);
      }
      // We replace content of current node with what was after [ndex ...]
      n.nodeValue=matches[3];
    }
  }
}

$(function(){
  // Get the elements we want to scan ( being sharper would be better )
  $('body').each(function(){
    // Passing them to function ndex_treat
    ndex_treat(this);        
  });

  // Make the ajax calls
  $('.ndex-to-replace').each(function(){
    // Don't know if necessary
    var current= this;
    $.get('call.php?ndex='+encodeURIComponent(this.title),function(data){
      $(current).replaceWith(data);
    });
  });
});

我用 node 而不是 jquery 替换,因为我发现用 jquery 在 textNode 上工作相当糟糕。如果您不在乎并且宁愿以野蛮人的方式行事,则可以简单地将所有第一部分替换为:

$(function(){
  // Get the elements we want to scan ( being sharper would be better )
  $('body').each(function(){
    // With no " in argument of [ndex ...]
    $(this).html( $(this).html().replace(/\[ndex\s+([^"]*?)\]/mg,'<span class="ndex-to-replace" title="$1"></span>') );
    // With no ' in argument of [ndex ...]
    //$(this).html( $(this).html().replace(/\[ndex\s+([^']*?)\]/mg,'<span class="ndex-to-replace" title='$1'></span>') );
  });

  // Make the ajax calls
  /* ... */
});

【讨论】:

  • 非常感谢。您给出的答案适用于复制+粘贴。棒极了! :) 但是,我仍然会尝试使用 Pablo 建议的解决方案。在我运行之前,我会使用你的解决方案。您帮助我更好地理解了 Javascript 中搜索/替换的工作方式,感谢您的帮助!
【解决方案2】:

我的建议是尽量减少 ajax 调用。首先进行搜索,然后在另一轮将每个对象替换为相应的数据。

$(document).ready(function() {
var pattern = /\[ndex\s+(.*?)\]/mg;
var documentText = $(document.body).text();
var matches = documentText.match(pattern);


$.ajax({ 
       url:'call.php',
       method:'POST',
       data: matches,
       success: function(data){
          //replace every matched element with the corresponding data
       });


}); 

您必须修改您的 call.php 以考虑到这一点,但您会节省大量对服务器的调用,从而节省时间

【讨论】:

  • 谢谢!这很棒!我有点担心将 javascript 对象传递给 php 文件,但我很确定我会找到如何操作它。然而,我的实际问题是:我需要用 html 代码(由我的 php 文件生成)替换 bb 代码,我不知道如何用相应的 html 代码替换文档中的文本从一个对象派生 (?)。有什么建议吗?
  • 你可以只做data:{ndex:matches}你将可以访问它作为 $_POST['ndex'] php页面中的一个数组,以替换dom节点或innerHTML(或等效的jquery html ())
  • 非常感谢你们,你们太棒了! :)
猜你喜欢
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 2011-02-20
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多