更好的方法来管理重复的id名称...属性

时间:2013-06-29 04:30:10

标签: php javascript html css

我在一个可以接收多个HTML片段的项目中工作,每个片段可以从不同的用户发送,实际上一些片段可以包含相同的id名称或CSS类名,如何管理重复的名称,并将其定位到JSPHP DOM

2 个答案:

答案 0 :(得分:1)

如果您可以将片段存储在JavaScript(AJAX或其他)中,那么您可以在页面上尝试这个 - 它应该可以在任何设备上运行并通过在将其添加到DOM之前使用随机数重命名来修复任何重复的ID < / p>

Live Demo

 $(function() {
  var counter=0,prefix="renFrag",fragments = [
      $('<div id="id1">Fragment1</div>'),
      $('<div id="id2">Fragment2</div>'),
      $('<div id="id3">Fragment3</div>')
  ]  
  $.each(fragments,function() {
      var id = $(this).attr("id"); // the ID of the fragment
      if ($("#"+id).length>0) { // find if this ID is already in the DOM
    // rename the fragment. NOTE Date().getTime() was not random enough 
    // $(this).attr("id",id+'_'+Math.floor(Math.random() * 10000)); 
        $(this).attr("id",prefix+(counter++)); 
      }  
      $(this).appendTo("#container"); // add the fragment to the DOM
  });
  $("div").each(function() { // display the ID for debugging (remove when happy)
      $(this).append("-"+this.id); 
  });  
});

如果您需要访问新片段,请为其添加固定字符串,将随机数更改为计数器并使用$("div[id^=renFrag]").whatever$("div[id=renFrag"+cnt+"]").whatever

如果您需要保留嵌入式脚本和CSS,那么通常不推荐但您的情况特殊的选项是将每个片段加载到自己的iFrame中。请注意,在页面中或通过iFrame执行外部脚本存在安全风险。

答案 1 :(得分:-1)

如果您知道要搜索的唯一ID,可以使用PHP中的str_replace轻松替换完整的字符串:

$html = str_replace(array('id="test1"', 'id="test2"'), array('id="new1"', 'id="new2"'), $html);

要在PHP中搜索并替换字符串中的CSS类名,可以使用preg_replace。 HTML节点上可能有多个类名,因此正则表达式可以更好地解析它。