运行 javascript WooCommerce 结帐时更改账单国家/地区的代码
Run javascript code on billing country change in WooCommerce checkout
嘿,我正在尝试 运行 一个功能,并在用户 select 美国以外的任何其他国家/地区时显示一条消息。但是,我被卡住了,因为我什至无法获得 select 框来记录更改国家/地区的事件。这是我的代码:
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
关于为什么会发生这种情况的任何想法? Woocommerce 是否阻止 JS 运行在页面上或其他什么?
编辑:JS Fiddle:https://jsfiddle.net/suoc57mg/1/
假设您的 #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>
你可以通过你这样处理的事件的target值来查看它的值
document.getElementById("billing_country")?.addEventListener("change", (event) => {
if (event.target.value !== "US") {
// not united state :(
}
});
您需要将事件委托给文档正文,否则 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
});
});
现在应该可以了。
嘿,我正在尝试 运行 一个功能,并在用户 select 美国以外的任何其他国家/地区时显示一条消息。但是,我被卡住了,因为我什至无法获得 select 框来记录更改国家/地区的事件。这是我的代码:
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
关于为什么会发生这种情况的任何想法? Woocommerce 是否阻止 JS 运行在页面上或其他什么?
编辑:JS Fiddle:https://jsfiddle.net/suoc57mg/1/
假设您的 #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>
你可以通过你这样处理的事件的target值来查看它的值
document.getElementById("billing_country")?.addEventListener("change", (event) => {
if (event.target.value !== "US") {
// not united state :(
}
});
您需要将事件委托给文档正文,否则 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
});
});
现在应该可以了。