[英]Unable to run the following js code in IE11 or IE9
我用一些 js 代碼制作了一個簡單的 html 頁面,我使用了所有 vanilla JS 並檢查了是否使用了與 IE 兼容的所有功能。
問題是以下頁面必須在 Google Chrome 中運行,而在 IE 中它不起作用,我在 IE11 和 IE9 中嘗試過,但在兩者中都不起作用。
該代碼只是將點擊事件添加到三個按鈕,按鈕 + / - 改變輸入和確認按鈕內的數量。
js看起來像這樣:
<script>
const btns = document.querySelectorAll('.btn-qty');
const confirms = document.querySelectorAll('.btn-success');
const inputs = document.querySelectorAll('.qty')
confirms.forEach(function(confirm) {
confirm.addEventListener('click', confirmHandler);
});
function confirmHandler(event) {
event.preventDefault();
let product_id = this.getAttribute("data-product-id");
let option_id = this.getAttribute("data-option-id");
let iva = parseInt(this.getAttribute("data-iva"));
let price = this.getAttribute("data-price");
let qty = this.getAttribute("data-qty");
window.location.href = "_?productId=" + product_id + "&optionId=" + option_id + "&iva=" + iva + "&price=" + price + "&qty=" + qty
}
inputs.forEach(function(input) {
input.addEventListener('change', function(event) {
event.preventDefault();
let btn = input.parentNode.querySelector(".input-group-prepend").querySelector('.btn-qty');
let confirm = input.parentNode.parentNode.querySelector('.btn-success')
let curVal = parseInt(input.value)
confirm.setAttribute('data-qty', curVal)
if (curVal >= 1) {
btn.removeAttribute('disabled');
}else if(curVal <= 1){
btn.setAttribute('disabled', true);
}
});
});
btns.forEach(function(btn) {
btn.addEventListener('click', function(event) {
event.preventDefault();
let input = btn.parentNode.parentNode.querySelector('.qty')
let curVal = parseInt(input.value)
let type = btn.getAttribute("data-type");
if (type == 'minus') {
if (curVal > 1) {
input.value = curVal - 1
input.dispatchEvent(new Event('change'));
}
if (parseInt(input.value) == 1) {
btn.setAttribute('disabled', true)
}
}else if (type == 'plus'){
input.value = curVal + 1
input.dispatchEvent(new Event('change'));
}
});
});
</script>
這是在 Chrome(頂部)和 IE11(底部)上運行的相同代碼
這是代碼的JSfiddle
我同意 Ivar 的建議。 我們需要在 IE 中為forEach
添加 polyfill,然后它可以與 IE 中的 NodeList 和 HTMLCollection 一起使用。 請添加以下 polyfill:
var ctors = [typeof NodeList !== "undefined" && NodeList, typeof HTMLCollection !== "undefined" && HTMLCollection];
for (var n = 0; n < ctors.length; ++n) {
var ctor = ctors[n];
if (ctor && ctor.prototype && !ctor.prototype.forEach) {
ctor.prototype.forEach = Array.prototype.forEach;
if (typeof Symbol !== "undefined" && Symbol.iterator && !ctor.prototype[Symbol.iterator]) {
Object.defineProperty(ctor.prototype, Symbol.iterator, {
value: Array.prototype[Symbol.itereator],
writable: true,
configurable: true
});
}
}
}
此外,在 IE 中這一行還有另一個錯誤:
input.dispatchEvent(new Event('change'));
您需要使用以下代碼在 IE 中使用dispatchEvent
:
var event = document.createEvent("Event");
event.initEvent("change", false, true);
input.dispatchEvent(event);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.