javascript - 如何测试一个类是否包含在一个 div id 中
问题描述
我正在为编码训练营制作一个简单的口袋妖怪纸牌游戏,当玩家点击任何口袋妖怪 id(#pikachu
等#squirtle
)时,它会出现在一个名为 的 div id 中#playerArea
,点击的下一个口袋妖怪 id 应该出现在#defenderArea
. 我需要测试是否有任何共享一个类的元素.pokemon
在#playerArea
使下一个被点击的口袋妖怪出现在#defenderArea
下面的 HTML 和脚本(不包括 css)
<body>
<header>
<h1>Pokemon Stadium</h1>
</header>
<div id="selectionArea">
<!-- pokemon cards share class but have their own IDs -->
<div id="pikachu" class="pokemon">
<img src="pikachu.png" height="200px" width="200px">
<span id="pikachuHp">100</span>
</div>
<div id="bulbasaur" class="pokemon">
<img src="bulbasaur.jpg" height="200px" width="200px">
<span id="bulbasaurHp">200</span>
</div>
<div id="charmander" class="pokemon">
<img src="charmander.png" height="200px" width="200px">
<span id="charmanderHp">150</span>
</div>
<div id="squirtle" class="pokemon">
<img src="squirtle.jpg" height="200px" width="200px">
<span id="squirtleHp">120</span>
</div>
<div id="mario" class="pokemon">
<img src="mario.jpg" height="200px" width="200px">
<span id="marioHp">300</span>
</div>
</div>
<!-- Enemies are moved here upon selection-->
<div id="defenderArea">
</div>
<!-- The players pokemon goes here-->
<div id="playerArea">
<button type="button" id="attackBtn" class="btn btn-primary">Attack</button>
</div>
<!-- Scripts & jQuery -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('#pikachu').click(function() {
$("#pikachu").appendTo("#playerArea");
});
});
$(document).ready(function() {
$('#squirtle').click(function() {
$("#squirtle").appendTo("#playerArea");
});
});
$(document).ready(function() {
$('#charmander').click(function() {
$("#charmander").appendTo("#playerArea");
});
});
$(document).ready(function() {
$('#bulbasaur').click(function() {
$("#bulbasaur").appendTo("#playerArea");
});
});
$(document).ready(function() {
$('#mario').click(function() {
$("#mario").appendTo("#playerArea");
});
});
if ( $('#playerArea').hasClass(".pokemon") ) {
//do something
alert("theres a pokemon in the playerArea");
};
</script>
我应该使用 if/else 语句来测试 playerArea 还是应该使用 if/else 来查看是否点击了 ID?
解决方案
//find a count of how many pokemon are children of the playerArea
if( $('#playerArea').find('.pokemon').length > 0 ) {
//put pokemon in defender area
}
推荐阅读
- python - 如何将元素附加到一对坐标以制作多维列表?
- android - 在 Android Studion 中为两个 URL 使用 AsyncTask 时出现问题
- r - ggplot2:geom_bar 和 position_dodge:不以 x 轴为中心(因子)
- python-3.x - Python firebase_admin.credentials 没有属性 Certificate
- ruby-on-rails - 如何在不出现“我们很抱歉,但出了点问题”的情况下推送到 Heroku
- r - 如何根据列值在行上循环操作?R
- c - 如何在 C 中以适当的间距生成随机数?
- azure - 权限不足,无法完成操作 - 服务主体
- android-seekbar - 从 seekBar android 中删除数字
- reactjs - react-chartjs-2 在调整窗口大小之前不显示行