https://codepen.io/anon/pen/NLNVbM
<button class="button" onClick= "document.getElementById('demo').dataset('data-filter') = '.blue';">Test</button>
<button id="demo" class="button" data-filter=".orange"><h4>Color</h4></button>
我想在单击时将.orange更改为.blue。这行不通,我做错了什么?
答案 0 :(得分:1)
您没有正确访问data-
属性。阅读以下内容:https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
var filter = document.getElementById('demo').dataset.filter;
//Original data-filter value:
console.log(filter);
//Add a click event handler to the button:
document.querySelector('#changeFilter').addEventListener('click', function() {
filter = '.blue';
//Updated data-filter value
console.log(filter);
});
<button id="changeFilter" class="button">Test</button>
<button id="demo" class="button" data-filter=".orange"><h4>Color</h4>
</button>
答案 1 :(得分:0)
您都在错误地建立索引并调用HTMLElement.dataset
。您的onclick处理程序应改为阅读...dataset['filter'] = '.blue'
。
答案 2 :(得分:0)
<button class="button" onClick= " document.getElementById('demo').setAttribute('data-filter','.blue');">Test</button>
<button id="demo" class="button" data-filter=".orange"><h4>Color</h4></button>