とcorelationを見つけるために、クラスXとのdivを通じて、私は私に聞かせスクリプト記述しようとしています:ループのdiv Y
- ループを通して各
id
- 、変数としてループを設定
- を見つけてcoresponds。私がこれまで書いてきた
.display-player-box
要素スルークラス属性のどの部分を見つけるため
.removefromsquad
要素がcoresponding要素が、私はマッチし、この特定の
.display-player-box
にクラス
.selected
を追加したい発見された場合、以前に
.display-player-box
id
、
コード:
$(".display-player-box").each(function() { // start looping
$selected = 0; // set a variable to default
$boxid = $(this).attr("id"); // set id of element being looped as variable
$(".removefromsquad").each(function() { // loop through another row of elements
if ($(this).attr("class").slice(16, 17) == $boxid) { // looking for part of it's class matching previously saved variable
$selected = 1; // if yes, update variable
};
});
if ($selected == 1) { // if variable was updated...
$(this).addClass("selected"); // add class to .display-player-box
} else { // if not...
$(this).removeClass("selected"); // make sure it's removed
}
});
問題がある - それは単に、動作しない要素が一致したときにクラスを追加しません。コンソールにエラーはありません。私は間違って何をしていますか?
$(".display-player-box").each(function() {
$selected = 0;
$boxid = $(this).attr("id");
$(".removefromsquad").each(function() {
if ($(this).attr("class").slice(16, 17) == $boxid) {
$selected = 1;
};
});
if ($selected == 1) {
$(this).addClass("selected");
} else {
$(this).removeClass("selected");
}
});
.selected {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Team slots:</p>
<div class="removefromsquad">EMPTY SLOT</div>
<div class="removefromsquad">EMPTY SLOT</div>
<div class="removefromsquad 3">PLAYER #3</div>
<div class="removefromsquad 4">PLAYER #4</div>
<p>Players to fill slots:</p>
<div class="display-player-box" id="1">PICK PLAYER #1</div>
<div class="display-player-box" id="2">PICK PLAYER #2</div>
<div class="display-player-box" id="3">PICK PLAYER #3</div>
<div class="display-player-box" id="4">PICK PLAYER #4</div>
質問/エラー/問題は何ですか? –
[最小、完全、および検証可能な例](https://stackoverflow.com/help/mcve) –
@ stephen.vakilを提供してください。質問が更新されました。最初は不明であったことに気付かなかった –