当我通过名为toggleState的函数单击按钮时,我试图在多个元素中设置和切换数据状态属性。
想法是,通过单击所选按钮来更改所有将受影响的元素的数据状态。首先,被单击的按钮元素必须更改为下一个状态。然后是其他元素。
如果其余参数中的元素没有“数据状态”,则会添加新的父亲状态。
我已经尝试在底部编写函数。但显示相同的消息错误。
我与MAMP和gulp一起处理结果。
//define button for action
var menuMobileButton = document.getElementById('menuMobileBtn');
//define function for change state in elements that will be affected
const toggleState= (state1, state2, ...elements) => {
//get the current parent state -doesn't work :(-
var parentCurrentState = this.getAttribute('data-state');
//set new state in the parent, -doesn't work too
this.setAttribute('data-state', parentCurrentState === state1 ? state2 : state1);
//set in all elements the new attribute, if doesn't have, add it
for (const element of elements){
if ( !element.hasAttribute('data-state') ){
element.setAttribute('data-state', this.getAttribute('data-state'));
}
element.setAttribute('data-state', element.getAttribute('data-state') === state1 ? state2 : state1);
}
};
//calling function when click
menuMobileButton.onclick = function (e) {
toggleState('closed', 'open', '#mainMenu', '.lineMenuBtn');
e.preventDefault();
}
这是codepen:https://codepen.io/jhossq/pen/eYYZrEP
我希望通过主按钮等参数发送的元素中的数据状态发生变化。
单击时,切换到按钮本身和参数发送的其他元素中的数据状态。