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

时间:2018-03-26 22:05:15

标签: javascript html5 dom custom-data-attribute

我有一个文本输入框,用户可以在其中输入他们想要在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,但无法弄明白。看起来你必须在驼峰的情况下传递数据属性,但可能无法通过变量来做?

提前致谢。

1 个答案:

答案 0 :(得分:1)

当您需要通过变量访问对象属性时,需要使用array-bracket语法。

在下面的示例中,键入&#34; data-test&#34;进入文本框,然后点击 TAB

&#13;
&#13;
// 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);
});
&#13;
<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>
&#13;
&#13;
&#13;