是否可以使用jquery移动数组元素?如果我点击它,它也会追加到数组中而不仅仅是在dom上?
var cardsInHand = ["1", "2", "3", "4", "5", "6", "7"];
var cardsOnField = [];
const cardsInHandEl = document.querySelector("#cardsInHand-el");
for (var i = 0; i < cardsInHand.length; i++) {
cardsInHandEl.innerHTML +=
`
<button>
${cardsInHand[i]}
</button>
`
}
$(document).on("click", "#cardsInHand-el button", function () {
$("#onField-el button")
.remove()
$(this)
.appendTo($("#onField-el"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<ul id="cardsInHand-el">Cards in Hand: </ul>
<ul id="onField-el"></ul>
<script src="script.js"></script>
</body>
您可以使用Array#push
将项目推入数组,Array#splice
在click
事件侦听器中删除。
var cardsInHand = ["1", "2", "3", "4", "5", "6", "7"];
var cardsOnField = [];
const cardsInHandEl = document.querySelector("#cardsInHand-el");
for (var i = 0; i < cardsInHand.length; i++) {
cardsInHandEl.innerHTML +=
`
<button>
${cardsInHand[i]}
</button>
`
}
$(document).on("click", "#cardsInHand-el button", function() {
$("#onField-el button")
.remove()
$(this)
.appendTo($("#onField-el"));
const number = $(this).text().trim();
cardsOnField.push(number);
cardsInHand.splice(cardsInHand.indexOf(number), 1);
/* debugging purposes only */
console.clear();
console.log('Cards in hand: ' + cardsInHand);
console.log('Cards on field: ' + cardsOnField);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<ul id="cardsInHand-el">Cards in Hand: </ul>
<ul id="onField-el"></ul>
<script src="script.js"></script>
</body>
UI库或多或少就是这么做的:
var cardsInHand = ["1", "2", "3", "4", "5", "6", "7"];
var cardsOnField = [];
const cardsInHandEl = document.querySelector("#cardsInHand-el");
const cardsOnFieldEl = document.querySelector("#onField-el");
function render(arr, el) {
el.innerHTML = '';
for (var i = 0; i < arr.length; i++) {
el.innerHTML +=
`
<button>
${arr[i]}
</button>
`
}
}
render(cardsInHand, cardsInHandEl);
render(cardsOnField, cardsOnFieldEl);
$(document).on("click", "#cardsInHand-el button", function () {
const number = $(this).text().trim();
cardsOnField.push(number);
cardsInHand.splice(cardsInHand.indexOf(number), 1);
render(cardsInHand, cardsInHandEl);
render(cardsOnField, cardsOnFieldEl);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<ul id="cardsInHand-el">Cards in Hand: </ul>
<ul id="onField-el"></ul>
<script src="script.js"></script>
</body>