简体   繁体   中英

Get all data attribute order of HTML elements

In the #content div, there are blocks that user can drag them and sort them. Each block may contain many nodes. Under each block, the are element that contains " data-node-id " attribute. i want to make a function that will get the order after drag-sort. this function can run from a click button (does not have to run for every sort-change).

Here is my page: http://orbitcoins.website/demos/demo%20-%20json_nodes_diagram/nodes_diagram_serverfile.php

So let's say, i have elements in this order:

order = {1,2,3,4,5}//block1:{1}, block2:{2}, block3:{3,4,5}

after changing the order of the second and the third block, When running this function, we will get this result:

new_order = {1,3,4,5,2}//block1:{1}, block2:{3,4,5}, block3:{2}

There is no difference when using JQuery or JavaScript.

Well, @Andreas has posted the solution in the comment:

$("[data-node-id]").map(function() { return +this.getAttribute("data-node-id"); }).get()

This solution seems perfect to me! it do exactly what i wanted to.

Credit Goes to @Andreas .

With this snippet, you can check all blocks in the order you defined and get the contained values at the end of the execution:

    // all the blocks you have
    $blocks = array(1, 2, 3);

    // all the elements they contain
    $blocks[1] = array(1);
    $blocks[2] = array(2);
    $blocks[3] = array(345);

    // the new block order you will get
    $new_order = array(1, 3, 2);

    // initialize the new blocks order
    $new_blocks = array();

    // for every block of the new order
    foreach ($new_order as $block) {

        // add to the new blocks order the content of that block
        array_push($new_blocks, $blocks[$block]);

    }

    // for each new block obtained
    foreach ($new_blocks as $block) {

        // and for every node inside
        foreach ($block as $item) {

            // print it out
            var_dump($item);

        }

    }

    // new_blocks is the structure you are searching for

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