【问题标题】:Insert tag in loop javascript在循环javascript中插入标签
【发布时间】:2021-07-19 16:40:43
【问题描述】:

我想在每个 rect 标签之后插入 p 标签,但不幸的是,当我使用 appendChild 时,p 标签被插入到 rect 标签而不是之后:

JS 代码

$("#id_svg .nv-series-0 rect").each(function(index){ 

var line = document.createElement("p");
  line.className = "line";
  line.innerHTML = '|';


this.appendChild(line);

)}

结果是: ** html代码:**

<svg id="id_svg">
    <g class="nv-series-0">
        <rect class="nv-bar positive">
            <p class="line">|</p>
        </rect>
    </g>
</svg>

【问题讨论】:

  • 如果您使用 jQuery,为什么不使用 jQuery? $(this).append('&lt;p class="line"&gt;|&lt;/p&gt;')?
  • 另外,如果您只看到一个p 输出,那么您只有一个来自#id_svg .nv-series-0 rect 的结果
  • 你尝试过使用 this.parent().appendChild(.....) 吗?
  • 不,我有几个 rect 标签,但我放了一个带有单个 rect 标签的代码示例。我的问题是我想在 rect 标签之后有 p 标签,而不是在其中。像那样

    PS:我使用了附加功能,但我遇到了同样的问题谢谢你的回复
  • 您不需要 JS 在列表中的每个元素后添加|。 CSS 可以用伪元素做到这一点:rect:after { content : "|"; }

标签: javascript html jquery safari


【解决方案1】:

您可以使用 Element.insertAdjacentElement 代替 appendChild(将其作为 child 插入其中)。

this.insertAdjacentElement('afterend', line);

【讨论】:

  • 但这太过分了。仅使用 CSS 就可以轻松完成(请参阅我上面的评论)
  • 感谢您的回复 Jeremy Thille 但我把角色 |简化我的代码。实际上 p 标签有几个属性(x,y,tronsform ...)是css不可能的:)@JeremyThille
猜你喜欢
  • 1970-01-01
  • 2015-03-16
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2021-07-12
  • 2016-08-15
相关资源
最近更新 更多