我想要一个方法来更新通过getter定义的属性的值。该属性获取HTML数据属性的值,方法mut将其递增1并在HTML中更新它。单击按钮时会调用该方法。比下次再次点击按钮时,我想getter重新定义属性的值,获取data-attribute的新值。但它不会发生。
环境允许我使用jQuery,因为作为构造函数的主要参数的“元素”是表示组件的HTML目标元素的jQuery对象。
这是代码:
import {Components} from 'MyCustomLibrary';
export default class Calendar extends Components{
get CurrentMonth(){
return this.element.data('calendar-currentmonth');
}
onClickHandler(){
this.getNewCalendar(this.CurrentMonth);
}
getNewCalendar(month){
/****
/* jQuery substituted with Vanilla for suggestion in the comments
$('[data-calendar-currentmonth]').data('calendar-currentmonth',month+1);
****/
let dataAttributes = document.querySelectorAll('[data-calendar-currentmonth]');//.data('calendar-currentmonth',month+1);
dataAttributes.forEach(function(e){
e.setAttribute('data-calendar-currentmonth',parseInt(month)+1);
});
}
constructor(element){
super(element) //element is the html target of component, and it's a jQuery object
this.element.on('click', this.onClickHandler.bind(this));
}
}
在html中我有我的按钮,它是一个带有'data-calendar-currentmonth = 2'属性的锚标签。最初设置为2,比我第一次点击,功能更新属性,我可以通过控制台在我的html DOM中看到“3”。
但是当我再次点击时,CurrentMonth的值再次为“2”,而且更多,html不再更新(可能只是因为属性值没有更新而且2 + 1总是3)。
每次调用它定义的属性时,是不是应该执行getter?那么为什么它没有在HTML中获得新值当它第二次被调用时?
实际上我发现它是jQuery造成的混乱。我简单地重新定义了Vanilla中的所有变量,它运行得很好。
我已经删除了get CurrentMonth
语句,我只是直接在getNewCalendar
的调用中传递它。
比我的代码变成这样:
onClickHandler() {
this.getNewCalendar(this.element[0].getAttribute('data-calendar-currentmonth'));
/*** 'this.element' is actually a jQuery object. Calling element[0] it comes back to plain js ***/
}
getNewCalendar(month) {
/****
/* jQuery substituted with Vanilla for suggestion in the comments
$('[data-calendar-currentmonth]').data('calendar-currentmonth',month+1);
****/
let dataAttributes = document.querySelectorAll('[data-calendar-currentmonth]');//.data('calendar-currentmonth',month+1);
dataAttributes.forEach(function(e) {
e.setAttribute('data-calendar-currentmonth', parseInt(month) + 1);
});
}
constructor(element) {
super(element) // element is the html target of component, and it's a jQuery object
this.element.on('click', this.onClickHandler.bind(this));
}