嘿,当用户选择美国以外的任何其他国家时,我正在尝试运行一个函数并显示一条消息。然而,我被卡住了,因为我甚至无法获得选择框来记录国家更改的事件。这是我的代码:
function checkIfInternational(e) {
console.log(e);
}
const shipCountry = document.querySelector("#billing_country"); //Logs the select box
shipCountry.addEventListener("change", checkIfInternational); // listening for the change event
你知道为什么会这样吗?Wooccommerce是否阻止JS在页面上运行?
编辑:JS Fiddle:https://jsfiddle.net/suoc57mg/1/
您需要将事件委托给文档主体,否则WooCommerce将在签出时阻止您的代码。
由于WooCommerce JS代码已经使用jQuery,请尝试以下操作:
jQuery(function($){
$(document.body).on('change', 'select[name=billing_country]', function(){
console.log('Country changed: '+$(this).val());
// Here run your function or code
});
});
现在应该可以了。
假设您的#billing_country元素如下所示:
<select id="billing_country">
<option value="US">United State</option>
<option value="PL">Poland</option>
<option value="DU">Germany</option>
<option value="ES">Estonia</option>
<option value="RU">Mather Russia</option>
</select>
您可以通过您以这种方式处理的事件的目标值来检查其值。
document.getElementById("billing_country")?.addEventListener("change", (event) => {
if (event.target.value !== "US") {
// not united state :(
}
});