简体   繁体   中英

How can I update multiple elements by class with unique sub data via JS?

In short, I have a string of 5-10 events I'm receiving from an external server that look like:

event: add
data: { "hostname":"name", "properties": {"info": "50"}}

event: add
data: { "hostname":"name2", "properties": {"info": "45"}}

event: add
data: { "hostname":"name3", "properties": {"info": "67"}}

etc, etc..

And I am processing them via EventSource JS like this:

var source = new EventSource("http://XXX.XXX.XXX.XXX:PORT/")
source.addEventListener('add', onAdd)

function onAdd(e) {
  var data = parse(e)

  var output = document.getElementById('append');
  var ele = document.createElement("div");
  var frag = document.createDocumentFragment();
  frag.appendChild(ele);
  ele.setAttribute("class", 'row sub-item');
  ele.innerHTML ="<ul>"
                +"<li>" + "<span id=name>" + data.hostname + "</span>" + "</li>"
                +"<li>" + "INFO: " + "<span id=info>" + data.properties.info + "</span>" + "</li>"
                +"</ul>"
                +"</div>"
  output.appendChild(frag);
}

This code successfully adds each div and the unordered list inside it onto the page.

My problem is that I have another set of future events like:

event: update
data: { "hostname":"name", "properties": {"info": "65"}}

event: update
data: { "hostname":"name2", "properties": {"info": "35"}}

event: update
data: { "hostname":"name3", "properties": {"info": "15"}}

etc..

and these come from the server and send the new info property every so often. I can't find a way to update the all the unique info properties by using span class ( <span class="info" ) because if I sort by class it updates every single info property on the page with the same number (name1 45 name2 45 name3 45) and I can't use id ( <span id="info" ) because then it will only update the first one since id is only supposed to be used once on your page.

I know there has to be a simple solution for this that I am overlooking. Thanks!

You could use datasets by adding a data-id attribute to each span, and then update only matches.

You could also alter your id to info_45 etc, and get id for each span, and use regex to get the id cleanID = idFromSpan.match(/\\d+/g)[0];

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