简体   繁体   English

如何使用用户输入动态传递数据集属性?

[英]How do I pass a dataset attribute dynamically using user input?

I have a text input box where a user inputs what data-* they want to look for in the DOM. 我有一个文本输入框,用户可以在其中输入要在DOM中查找的data- *。 I get this user input on a button click then do a little bit of parsing. 我在单击按钮时得到该用户输入,然后进行一些解析。 How would I get the value of the entered text to be the final part of the HTMLElement.dataset selector? 如何将输入的文本的值作为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);

I have read this from MDN Developers but can't figure it out. 我看了这个从MDN开发,但不能弄明白。 It looks like you have to pass the data attribute in camel case but might not be able to do it via a variable? 看起来您必须在驼峰式的情况下传递data属性,但是可能无法通过变量来实现?

Thanks in advance. 提前致谢。

When you need to access an object property via a variable, you need to use array-bracket syntax. 当需要通过变量访问对象属性时,需要使用数组括号语法。

In the example below, type "data-test" into the text box and then hit TAB . 在下面的示例中,在文本框中键入“ data-test”,然后单击TAB

 // Get a reference to the input var specificSelector = document.getElementById("specificSelector"); var a = document.getElementById("a"); // Test element // Set up an event handler for when the data is changed and the // input loses focus specificSelector.addEventListener("change", function(){ // Extract the custom name portion of the data- attribute var parsedSelector = specificSelector.value.match(/data-(.*)/)[1]; console.log("Parsed selector: ", parsedSelector); // Pass the string (stored in the variable) into the dataset object // of another element to look up the object key. var aData = a.dataset[parsedSelector]; console.log("aData: ", aData); }); 
 <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> <div id="a" data-test="test2"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM