【发布时间】:2018-09-05 04:24:01
【问题描述】:
我有一个文本输入框,用户可以在其中输入他们想要在 DOM 中查找的数据-*。我通过单击按钮获得此用户输入,然后进行一些解析。如何让输入文本的值成为 HTMLElement.dataset 选择器的最后一部分?
//HTML for text input
<div class="form-group">
<label for="specificSelector">Specific Selector</label>
<input type="text" class="form-control" id="specificSelector" placeholder="Enter the specific selector here">
</div>
<p id="a"></p>
//JavaScript
var specificSelector = document.getElementById("specificSelector").value;
var a = document.getElementById("a"); // Test element
var parsedSelector = specificSelector.match(/data-(.*)/)[1];
console.log("Parsed selector: ", parsedSelector);
//I need to pass the value of the parsedSelector to the below line
var aData = a.dataset.parsedSelector;
console.log("aData: ", aData);
我已阅读 MDN 开发人员的 this,但无法弄清楚。看起来您必须以驼峰形式传递 data 属性,但可能无法通过变量来传递?
提前致谢。
【问题讨论】:
-
a定义在哪里? -
什么是
a?另一个元素? -
是的,这是我未能在示例中包含的另一个元素。我现在把它加进去了。
标签: javascript html dom custom-data-attribute