简体   繁体   中英

read html object and replace javascript properties with read values

I have a JavaScript parameter object with some HTML content in the following structure.

function (type, content, title) { 

  // Replace code should go here

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

The content of the content object looks as follows:

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

I would like to read out the data- parameters from the HTML div and assign them to replace the same named function in the JavaScript function.

All of this should happen at the top of my JavaScript function and replace the properties in the same function.

Thanks for any help or pointers how to achieve this, I am not very skilled at 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" />

What I would do (assuming jQuery):

  • create an invisible div in your html

  • set the innerHTML of the div

  • set the attributes from those of the invisible div to your object:

 $("#invisible").html(content); options["data-onclick"] = $("#invisible").find("#content").attr("data-onclick"); options["data-progress"] = $("#invisible").find("#content").attr("data-progress"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="invisible" style="display: none;"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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