我将以下代码用于带有Siema的滑块:
https://codepen.io/pawelgrzybek/pen/boQQWy
使用扩展类在幻灯片上添加点。一切正常,除了我们的网站现在出现使用ES6的Google移动友好测试问题,因为它会显示错误:
Uncaught SyntaxError: Unexpected reserved word
在此行:
class SiemaWithDots extends Siema {
有没有办法使它与ES5兼容?
代码如下:
// instantiate new extended Siema
const mySiemaWithDots = new SiemaWithDots({
// on init trigger method created above
onInit: function(){
this.addDots();
this.updateDots();
},
// on change trigger method created above
onChange: function(){
this.updateDots()
},
});
// extend a Siema class by two methods
// addDots - to create a markup for dots
// updateDots - to update classes on dots on change callback
class SiemaWithDots extends Siema {
addDots() {
// create a contnier for all dots
// add a class 'dots' for styling reason
this.dots = document.createElement('div');
this.dots.classList.add('dots');
// loop through slides to create a number of dots
for(let i = 0; i < this.innerElements.length; i++) {
// create a dot
const dot = document.createElement('button');
// add a class to dot
dot.classList.add('dots__item');
// add an event handler to each of them
dot.addEventListener('click', () => {
this.goTo(i);
})
// append dot to a container for all of them
this.dots.appendChild(dot);
}
// add the container full of dots after selector
this.selector.parentNode.insertBefore(this.dots, this.selector.nextSibling);
}
updateDots() {
// loop through all dots
for(let i = 0; i < this.dots.querySelectorAll('button').length; i++) {
// if current dot matches currentSlide prop, add a class to it, remove otherwise
const addOrRemove = this.currentSlide === i ? 'add' : 'remove';
this.dots.querySelectorAll('button')[i].classList[addOrRemove]('dots__item--active');
}
}
}
答案 0 :(得分:2)
然后您将class
替换为老式的构造函数,然后操纵原型以建立原型层次结构:
function SiemaWithDots() {
Siema.apply(this, arguments);
}
SiemaWithDots.prototype = Object.create(Siema.prototype);
SiemaWithDots.prototype.constructor = SiemaWithDots;
SiemaWithDots.prototype.addDots = function () {
// ... your code ...
};
SiemaWithDots.prototype.updateDots = function () {
// ... your code ...
};
答案 1 :(得分:0)
当前,您的代码包含许多ES6功能-const
,class
,箭头功能。您应该使用Babel.JS之类的在线编译器来使代码与ES5兼容。
此外,在您的代码中,在定义它之前,您正在使用一个类。好的做法是将所有类定义和箭头函数移到代码的顶部(在评估任何代码之前,先找到常规的ES5函数)。因此您的代码应该看起来像:
class SiemaWithDots extends Siema {...}
const mySiemaWithDots = new SiemaWithDots({...});