【问题标题】:How do I pass a dataset attribute dynamically using user input?如何使用用户输入动态传递数据集属性?
【发布时间】: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


【解决方案1】:

当您需要通过变量访问对象属性时,您需要使用数组括号语法。

在下面的示例中,在文本框中键入“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>

【讨论】:

  • 非常感谢!这就像一个魅力,不敢相信我忘了使用数组括号语法。谢谢!
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多