繁体   English   中英

使用javascript / jquery删除特定的html代码

[英]Remove specific html code using javascript/jquery

<div id="mn">

    <p article="game" a_type="advertisement" cid="#P6_001"></p> 
    <p article="let" cid="#P6_005"></p> 
    <dc_title article="start" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
    <p article="end" cid="#P6_047"></p> 
    <p article="start" a_type="advertisement" cid="#P6_001"></p> 
    <p article="end" cid="#P6_005"></p> 
    <dc_title article="sd" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
    <p article="end" cid="#P6_047"></p> 
</div>

我有这样的代码。 我想删除具有article =“ start”属性的标签,而下一个具有article =“ end”属性的标签

<dc_title article="start" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
<p article="end" cid="#P6_047"></p> 

所以在修复上面的代码后,我想像这样显示它:

<p article="game" a_type="advertisement" cid="#P6_001"></p> 
<p article="let" cid="#P6_005"></p> 
<dc_title article="sd" check_zone="true" a_type="masthead" cid="#P6_006"></dc_title> 
<p article="end" cid="#P6_047"></p>

如果您愿意使用jQuery(或者在项目中可以使用),则可以执行以下操作:

elements = $('[article="start"] + [article="end"]');
elements.prev().detach();
elements.detach();

第一行选择所有具有article=end的元素,紧接其后是article=start的元素。 第二行删除article=start元素,第三行删除article=end元素。

您可以使用jQuery jsfiddle解决

     var selector1=$( 'p[article="start"]');
     var selector2=$( 'dc_title[article="start"]');
     selector2.next('p[article="end"]').remove();
     selector1.next('p[article="end"]').remove();
     selector1.remove();
     selector2.remove();

使用var dv = getElementsByAttribute('article','start');获得对节点的引用var dv = getElementsByAttribute('article','start');

for(var i=0;i<dv.length;i++){
 if(dv[i].nextSibling.getAttribute('article')=="end")
    var ref = dv[i];
    ref.parentNode.removeChild(ref.nextSibling);
    dv[i].parentNode.removeChild(dv[i]); 

 }



var getElementsByAttribute = function (attr, value) {
  var match = [];

  /* Get the droids we're looking for*/
  var elements = document.getElementsByTagName("*");

  /* Loop through all elements */
  for (var ii = 0, ln = elements.length; ii < ln; ii++) {

    if (elements[ii].hasAttribute(attr)) {

      /* If a value was passed, make sure it matches the element's */
      if (value) {

        if (elements[ii].getAttribute(attr) === value) {
          match.push(elements[ii]);
        }
      } else {
        /* Else, simply push it */
        match.push(elements[ii]);
      }
    }
  }
  return match;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM