gpt4 book ai didi

javascript 函数不能运行两次

转载 作者:行者123 更新时间:2023-12-02 17:10:07 24 4
gpt4 key购买 nike

我正在自学编写原生 JavaScript,我创建了这个函数来检查 div 是否有子元素,如果没有,则创建一个带有“card”类的 div。

当我传入一个参数时,该函数可以工作,但是当我连续执行时,它会忽略第一个函数实例,只输出第二个函数实例。有任何想法吗?

谢谢!

这是我的代码:

JavaScript:

var dealerCards = document.querySelector('.dealer-cards');
var playerCards = document.querySelector('.player-cards');
var newDiv = document.createElement('div');

function cardCheck(a){
if (a.firstChild == null) {

console.log(a.firstChild, a);

newDiv.className = 'card';

return a.appendChild(newDiv);

}
}

cardCheck(dealerCards);
cardCheck(playerCards);

HTML:

<div class="dealer-box box">
<h2>Dealer</h2>
<div class="dealer-cards card-wrapper"></div>
</div>
<div class="player-box box">
<h2>Player</h2>
<div class="player-cards card-wrapper"></div>
</div>

http://jsbin.com/rehozu/1/edit?html,js

最佳答案

您必须在函数内创建新元素。如果您要附加文档中已存在的元素,该元素将移动到其新的父元素,而不是克隆。

来自MDN documentation :

If child is a reference to an existing node in the document, appendChild moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).

This also means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.

You can use Node.cloneNode to make a copy of the node before appending it under the new parent. (Note that the copies made with cloneNode will not be automatically kept in sync.)

关于javascript 函数不能运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com