简体   繁体   English

删除<span>一个</span> <div>

[英]Removing a <span> in a <div>

I have the following code: 我有以下代码:

<div id="weeks"> 
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span>10</span>
</div>

I want to be able to call a JavaScript function that will remove the first <span> whenever I call it (so the first time I call it, it'll remove the <span> with 1 in it, the next time 2, etc.), what's the best way to go about this? 我希望能够调用一个JavaScript函数,该函数将在每次调用它时删除第一个<span> (因此,当我第一次调用它时,它将删除其中带有1的<span> ,下次是2,依此类推。 。),执行此操作的最佳方法是什么?

Thank you! 谢谢!

Use this function: 使用此功能:

function removeFirst(selector){
   $(selector).children().first().remove();
}

So it takes the jquery selector as a parameter. 因此,它将jquery选择器作为参数。 Use it like this: 像这样使用它:

removeFirst('#weeks');

That will remove the first child every time you call it. 每次您调用它时,都会删除第一个孩子。

In plain JavaScript you could do: 在普通的JavaScript中,您可以执行以下操作:

var weeks = document.getElementById("weeks");
weeks.removeChild(weeks.firstElementChild);

JsFiddle Complete Example JsFiddle完整示例

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

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