首页 > 解决方案 > 读取 html 对象并用读取的值替换 javascript 属性

问题描述

我有一个 JavaScript 参数对象,其中包含以下结构中的一些 HTML 内容。

function (type, content, title) { 

  // Replace code should go here

  options = {
    "data-onclick": null; 
    "data-progress": false;
  }
}

内容对象的内容如下所示:

<div id=content data-onclick="onclickValue" data-progress="true"></div>

我想data-从 HTML div 中读出参数并分配它们以替换 JavaScript 函数中相同的命名函数。

所有这些都应该发生在我的 JavaScript 函数的顶部,并替换同一函数中的属性。

感谢您提供任何帮助或指示如何实现这一点,我对 JavaScript 不是很熟练。

标签: javascript

解决方案


// first select the html element
var element = document.getElementById('content');

// use the getAttribute('attribute-to-get') method to get your attributes 
var options = {
  'data-onclick': element.getAttribute('data-onlick'),
  'data-progress': element.getAttribute('data-progress')
};

// consider using a hidden input field rather than hiding the element with css 
// this is best practice
<input type="hidden" id="content" data-onclick="onclickValue" data-progress="true" />

推荐阅读