const allButtonsToStore = document.getElementsByClassName("button");
let reason = [];
for (let x=0; x < allButtonsToStore.length; x++) {
allButtonsToStore[x].addEventListener("click", function(){
reason[x] = this.textContent;
console.log("reason" + [x] + ": " + reason[x]);
reason[x] = this.value;
console.log("reason" + [x] + ": " + reason[x]);
reason[x] = this.data-spec;
console.log("reason" + [x] + ": " + reason[x]);
});
}
<div id="gamen" class="hidden">
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="ram" value="2GB">Lichte games</button>
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="videokaart" value="2GB">Middel games</button>
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="processor" value="i9">Zware games</button>
</div>
使用 JS,我可以获得所有按钮,并且为了进行测试,我会检查是否可以获得属性(稍后我需要属性和值)。
this.textContent;
和 reason[x] = this.value;
工作正常。只是我似乎无法弄清楚如何获取自定义属性 this.data-spec;
this.data-spec;
给出 ReferenceError:规范未定义
this."data-spec";
和 this."[data-spec]";
给出 SyntaxError: Unexpected string
this.[data-spec];
和 this.(data-spec);
给出意外的 token 错误
最佳答案
由于它是 HTML5 data-
属性,因此您实际上可以使用 HTMLElement.dataset 检索其值。 ,即
this.dataset.spec
查看概念验证示例:
const allButtonsToStore = document.getElementsByClassName("button");
let reason = [];
for (let x=0; x < allButtonsToStore.length; x++) {
allButtonsToStore[x].addEventListener("click", function(){
reason[x] = this.textContent;
console.log("reason" + x + ": " + reason[x]);
reason[x] = this.value;
console.log("reason" + x + ": " + reason[x]);
reason[x] = this.dataset.spec;
console.log("reason" + x + ": " + reason[x]);
});
}
<div id="gamen" class="hidden">
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="ram" value="2GB">Lichte games</button>
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="videokaart" value="2GB">Middel games</button>
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="processor" value="i9">Zware games</button>
</div>
但是,您的代码中有一点让我担心,那就是您不断地覆盖 reason[x]
。如果您稍后以某种方式使用数组 reason
,请注意,您只会获得最后一个值(即 data-spec
的值),而不是 >textContent
或元素的value
。
如果您熟悉使用 ES6,您的代码可以进一步优化:
const allButtonsToStore = document.querySelectorAll('.button');
allButtonsToStore.forEach((el, i) => {
el.addEventListener('click', () => {
console.log(`reason${i}: ${el.textContent}`);
console.log(`reason${i}: ${el.value}`);
console.log(`reason${i}: ${el.dataset.spec}`);
});
});
<div id="gamen" class="hidden">
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="ram" value="2GB">Lichte games</button>
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="videokaart" value="2GB">Middel games</button>
<button class='button' data-next="gamen1" data-parent="gamen" data-spec="processor" value="i9">Zware games</button>
</div>
关于javascript - 使用 JS 获取自定义 HTML 属性并与 "this"一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60206986/