我想要一个 javascript 函数来获取元素的数据属性。我想在原生 JS 元素上使用它。
我四处寻找原型吸气剂,但我无法理解它是如何工作的(javascript还不是我的一杯茶)。
我想要的是:
this.myCustomFunction('fooBar'); // the `this` element
document.getElementById('ExampleId').myCustomFunction('fooBar'); // another way of selecting
我找到的所有示例都是关于我自己创建的对象,我想要一个像上面的示例一样。
要提供基准,您可以在此处找到基准
如果有人能给我一个小例子,以及一些关于代码如何流动的解释,那就太好了(或者关于如何调用它,以供将来参考)。
第一条评论建议我不要这样做。如果有其他解决方案,我会多解释一下我的目标。这就是我现在的位置:
Object.prototype.cms_getDataAttr = function(dataname){
// IE upto 10 doenst work with dataset, so use the slower 'getAttribute'
if( typeof this.dataset == 'undefined'){
return this.getAttribute('data-'+dataname);
}
else{
// I want to use this one instead, benchmarked this is ALOT faster
return this.dataset.bigsrc;
}
}