【发布时间】:2018-07-23 11:03:19
【问题描述】:
默认情况下,Woocommerce 为我提供了产品自定义布局的选项。点击下面的按钮
但是,无论网络用户点击大尺寸,默认选择始终是小尺寸。我附上了演示代码来展示问题,我将是解决方案。我想使用 JS 来删除页面加载时的默认检查。然后单击按钮,大小将通过使用 html 上的数据键来确定主餐选择。
问题:我的大按钮单击有效,但小按钮单击不会更改检查的值。我们将不胜感激您的帮助或不同的看法。
window.onload = removePreSelection();
const clickBtns = Array.from(document.querySelectorAll('.defaultbtn'));
clickBtns.forEach(clickBtn => clickBtn.addEventListener('click', clickedBtnSelect));
//Remove the default selection of radio buttons on page.
function removePreSelection() {
const inputs = document.querySelectorAll('input[name=attribute_pa_sizes]:checked');
for (let i = 0; i < inputs.length; i++) {
const element = inputs[i];
element.removeAttribute("checked");
}
}
//Filter the values of the clicked button.
function clickedBtnSelect(e) {
removePreSelection();
const bentoSize = e.target.dataset.bento;
const bentoModal = e.target.dataset.target.replace(/([#]+)/gi, '');
const modalInputValue = document.querySelector('input[value=' + bentoSize + ']');
console.log(modalInputValue);
//set the attribute to checked.
modalInputValue.setAttribute("checked", "checked");;
}
<div class="show-pricing">
<p class="variable-pricing">
<span>Large: 27500</span>
<button class="btn defaultbtn" data-target="#myModal1900" data-toggle="modal" data-bento="large" type="button">Large</button>
</p>
<p class="variable-pricing">
<span>Small: 23000</span>
<button class="btn defaultbtn" data-target="#myModal1908" data-toggle="modal" data-bento="small" type="button">Small</button>
</p>
<!-- Modal -->
<div aria-labelledby="myModalLabel" class="modal fade" id="myModal1900" role="dialog" tabindex="-1">
<div class="variations">
<div class="col-md-4">
<h3 class="variations-options-head">Large Modal selected</h3>
<div class="value">
<fieldset>
<p>
<input id="pa_sizes" name="attribute_pa_sizes" type="radio" value="large">
<span class="radio-span">Large</span>
</p>
<p>
<input checked="checked" id="pa_sizes" name="attribute_pa_sizes" type="radio" value="small">
<span class="radio-span">Small</span>
</p>
</fieldset>
</div>
</div>
</div>
</div>
<!-- Modal 2 -->
<div aria-labelledby="myModalLabel" class="modal fade" id="myModal1908" role="dialog" tabindex="-1">
<div class="variations">
<div class="col-md-4">
<h3 class="variations-options-head">Small modal selected</h3>
<div class="value">
<fieldset>
<p>
<input id="pa_sizes" name="attribute_pa_sizes" type="radio" value="large">
<span class="radio-span">Large</span>
</p>
<p>
<input checked="checked" id="pa_sizes" name="attribute_pa_sizes" type="radio" value="small">
<span class="radio-span">Small</span>
</p>
</fieldset>
</div>
</div>
</div>
</div>
</div>
【问题讨论】:
-
我已经回答了一个工作和测试版本的 jQuery 女仆,更加紧凑和高效。请尝试一下。谢谢。
-
我对 jQuery 等其他选项持开放态度。谢谢
标签: javascript jquery html wordpress woocommerce