【问题标题】:add/remove specific html using javascript/jquery [closed]使用 javascript/jquery 添加/删除特定的 html [关闭]
【发布时间】:2014-08-17 21:57:44
【问题描述】:

我有这样的代码:

<div id="sd">

    <dc_title article="start" check_zone="true" a_type="cover" cid="#P1_001"></dc_title>
    <p article_con="1.1" cid="#P1_013"></p>
    <p article="start" a_type="advertisement" cid="#P2_001"></p>
    <p article_con="2.1" cid="#P2_004"></p>
    <p article_con="2.1" cid="#P3_001"></p>
    <p article_con="2.1" cid="#P3_005"></p>
    <p article_con="2.1" cid="#P4_001"></p>
    <p article="end" cid="#P4_002"></p>
    <dc_title article="start" check_zone="true" a_type="tableOfContents" cid="#P5_001"></dc_title>
    <dc_title article="start" check_zone="true" create_section="true" a_type="article" cid="#P14_001"></dc_title>
    <p article_con="14.1" cid="#P14_040"></p>
    <p article_con="14.1" cid="#P16_005"></p>
    <p article="end" cid="#P16_018"></p>

</div>

还有3个特殊属性:

article="start"
article_con="...."
article="end"
  • 我想检查第一行标签是否有article="start" 属性,最后一行标签是否有article="end" 属性。

  • 我想查找附近有没有两个相同的标签(只考虑属性):

    <p article="end" cid="#P4_002"></p>
    <p article="end" cid="#P4_002"></p>
    

    <p article="start" cid="#P4_001"></p>
    <p article="start" cid="#P4_002"></p>
    

    OR article_con="..." 具有相同的值和奇数个标签:

    <p article_con="2.1" cid="#P3_001"></p>
    <p article_con="2.1" cid="#P3_002"></p>
    <p article_con="2.1" cid="#P3_003"></p>
    

【问题讨论】:

  • 标题与问题完全无关。

标签: javascript jquery html


【解决方案1】:
$sdChilds = $( "#sd" ).children();
if (($sdChilds.first().attr('article') == 'start') && ($sdChilds.last().attr('article') == 'end')){
    alert('Yes, first and last tags are Start and End');
}else{
    alert('No, first and last tags are not Start and End');
}

var prevArticle = '*';
var prevArticleCon = '*';
var i = 0;
var j = 0;
$("p, dc_title" ).each(function(){
    if (($(this).attr('article') == prevArticle) && (prevArticle != null)){
        i++;
    }
    if (($(this).attr('article_con') == prevArticleCon) && (prevArticleCon != null)){
        j++;
    }
    prevArticle = $(this).attr('article');
    prevArticleCon = $(this).attr('article_con');
});
if (i > 0){
    alert('Yes, you have '+ i + ' extra element with same article attribute');
}
if (j > 0){
    alert('Yes, you have '+ j + ' extra element with same article_con attribute');
}

Check this JSFiddle Demo

您可以更改HTML 代码并检查它是否可以正常工作。 尝试添加或删除开始和结束标签,添加或删除具有重复属性的标签并检查代码。

【讨论】:

  • 当我留下原始评论时,答案是指向其他地方发布的代码的链接,您的“答案”中只发布了少量评论。我的反对票只是为了解决这个问题,一旦你在这里发布你的代码就撤回了(就像你最初应该做的那样)。我不会评论代码的简单程度,因为对我来说 question 难以辨认,所以我无法评估您答案的正确性。
猜你喜欢
  • 2021-08-28
  • 2011-07-24
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
相关资源
最近更新 更多