简体   繁体   中英

Using Javascript to pull cell data from one table to another

I don't know if this is possible, and I've been digging around for code for hours with no luck, so I'm going to give this a shot.

Let's say I have a table on a page. It contains the following:

<table id="srctb">
    <tr>
        <td>Users</td>
        <td>Musers</td>
        <td>Abusers</td>
    </tr>
    <tr>
        <td>50</td>
        <td>34</td>
        <td>16</td>
    </tr>
</table>

On a different page, I have another table. It looks like this:

<table id="desttb">
    <tr>
        <td>Users</td>
        <td>Musers</td>
        <td>Abusers</td>
    </tr>
    <tr>
        <td> </td>
        <td> </td>
        <td> </td>
    </tr>
</table>

Without having to manually enter the values, like they are in the srctb table, I want to populate table desttb with the exact same values.

Is there a piece of javascript code that will fetch the value of a cell in table srctb, and stick it into a cell in table desttb?

Any help is greatly appreciated!

EDIT: If there isn't a way to do it with javascript, I do believe I can use jquery to a certain extent, but I'm not sure. I know there are better ways to do this, but unfortunately the site where this needs to work is rather limited in capability.

You could save the content of the table in a localstorage object.

page 1:

window.onbeforeunload = function() { // when you switch page
  localStorage.setItem("content", document.getElementById("from").innerHTML); // save the data to localstorage
};

page 2:

window.onload = function () {
  var content = localStorage.content;
  if (content !== undefined) {
    document.getElementById("to").innerHTML = content;
  }
}

I hope this works!

code example

Assuming you can use jQuery 1.8 or later, you should be able to do something like this:

$.get('/srctab.html').done(function(data) {
  $.parseHTML(data).find('#srctb > *').appendTo('#desttb');
});

This grabs the other page using AJAX, parses it as HTML, finds descendants of #srctb, and appends them to #desttb.

I haven't tested this yet, and it may run afoul of the idea that each table has an implicit or explicit tbody that contains the rows.

Also, if you need the actual data values instead of the whole row, you'll have to use a few more complicated selectors to get them, but the basic idea of grabbing the page and parsing it still applies.

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