英文:
How to make the script check all "item__sizes" for the number of child elements and replace parameters
问题
const checkWidth = () => {
const numberOfBtns = document.getElementsByClassName('item__sizes').childElementCount;
const checker = document.querySelector('.item__checker');
if (numberOfBtns === 2) {
checker.style.width = "50%";
}
if(numberOfBtns === 1) {
checker.style width = "100%";
};
};
checkWidth();
英文:
I need the script to find all "item__sizes" elements and count the number of child elements. If there are 2, then the width of "item__checker" = 50%. If 1, then the width of "item__checker" = 100%.
HTML (PHP)
<?php if ($product_attributes): ?>
<div id="item__sizes" class="item__sizes">
<?php $is_first_item = true; ?>
<?php foreach ($product_attributes as $attribute): ?>
<?php
$attribute_active_class = $is_first_item ? ' active' : '';
?>
<button class="item__size js-item__sizes_btn js-btn-product-attribute<?php echo $attribute_active_class; ?>"
data-product-attribute-price="<?php echo $attribute['price']; ?>"
data-product-attribute-value="<?php echo $attribute['name']; ?>" type="button"><?php echo $attribute['name']; ?></button>
<?php
$is_first_item = false;
endforeach;
?>
<div class="item__checker"></div>
</div>
<?php endif; ?>
JavaScript
const checkWidth = () => {
const numberOfBtns = document.getElementsByClassName('.item__sizes').childElementCount;
const checker = document.querySelector('.item__checker');
if (numberOfBtns === 2) {
checker.style.width = "50%";
}
if(numberOfBtns === 1) {
checker.style.width = "100%";
};
};
checkWidth();
答案1
得分: 0
问题是你只选择了一个item__sizes中的尺寸来进行测试。你需要遍历它们所有:
(function() {
let buttons = document.querySelectorAll('.item__sizes');
for (var i = 0; i < buttons.length; i++) {
var buttonLength = buttons[i].querySelectorAll('.item__size').length;
var checker = buttons[i].querySelector('.item__checker');
if (buttonLength === 2) {
checker.style.width = "50%";
}
if (buttonLength === 1) {
checker.style.width = "100%";
}
}
})()
英文:
The problem is you are only selecting one of your item__sizes to do the test. You need to loop through all of them:
(function() {
let buttons = document.querySelectorAll('.item__sizes');
for (var i = 0; i < buttons.length; i++) {
var buttonLength = buttons[i].querySelectorAll('.item__size').length;
var checker = buttons[i].querySelector('.item__checker');
if (buttonLength === 2) {
checker.style.width = "50%";
}
if (buttonLength === 1) {
checker.style.width = "100%";
}
}
})()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论