简体   繁体   中英

Add element to list using map function (javascript)

I have a list of buttons. Here, I display my buttons using a map function since the number of buttons is determined by the number of elements in a list, eg, "myList" has 4 letters. However, in other cases, the lists will contain a different number of letters.

The buttons are also colored based on the another list called "myColors" and this can also change in other cases.

However, I will always show the button "done" at the bottom of the button menu, although the length of the list will vary by case. I'd like this button to be placed in the same menu (#buttonGallery) so that the formatting is consistent. Does anyone know how to do insert the "done" button into the map function?

Many thanks in advance. (Any advice on editing this post to be more clear would also be appreciated.)

Code below: (for now, you can see that I directly set the position of the "done" button)

<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <style media="screen">
    .buttons {
      width: 150px;
      height: 50px;
      border: solid 2px black;
      text-align: center;
      color: black;
      cursor: pointer;
      background-color: white;
      margin: 2px;
    }

    #buttonGallery {
      margin: 10px;
      padding: 10px;
      border: solid 2px black;
      width: 155px;
    }

    #done {
      width: 150px;
      height: 50px;
      border: solid 2px black;
      text-align: center;
      color: black;
      cursor: pointer;
      background-color: white;
      margin: 2px;
    }
  </style>
</head>

<body>

  <div id="done">
    <p>done</p>
  </div>

  <script type="text/javascript">
    let $buttons = $('<div id="buttonGallery">');
    let myList = ["A", "B", "C", "D"];
    let myColors = ["red", "green", "blue", "red"];

    myList.map(function(letter, index) {
      let $button = $("<div></div>")
        .addClass("buttons")
        .attr("id", "button_" + letter)
        .html("<p>" + letter + "</p>")
        .on("mouseenter", function() {
          $(this).css("background", myColors[index]);
        })
        .on("mouseleave", function() {
          if (!$(this).hasClass('clicked')) {
            $(this).css("background", "transparent");
          }
        })
        .on("click", function() {
          $(this).css("background", myColors[index]);
          $(this).addClass('clicked');
        })
      $buttons.append($button);
    });

    $("body").append($buttons);

    $("#done").on("click", clearColor);

    function clearColor() {
      $(".buttons").css({
        backgroundColor: 'transparent'
      });
      $(".buttons").removeClass('clicked');
    }
  </script>
</body>

</html>

Here's what I hope the result to look like: 在此处输入图像描述

The quick answer is you can simply append it to the element holding the buttons:

$("#done").appendTo("#buttonGallery")

Here I took some liberty with your buttons to do less work, moving the behavior of the .on() outside the .map where you generate your buttons from the object values. How you get your values can be done several ways but using your arrays, I simply added the color to the button when I generated it as a data attribute that can be used to show/hide and "fix" the color on click. For fun, I also show how to "toggle" the color on a second click.

Since you are generating a div for your button gallery, I added that to the HTML instead to simplify the code a bit.

 let myList = ["A", "B", "C", "D"]; let myColors = ["red", "green", "blue", "red"]; let gallery = $("#buttonGallery");// cache the reference to use elsewhere myList.map(function(letter, index) { let $button = $("<div class='buttons'><p></p></div>"); $button.data("mycolor", myColors[index]).attr("id", "button_" + letter).find("p").html(letter); $button.appendTo(gallery); }); gallery.on("mouseenter", ".buttons", function() { $(this).css("background", $(this).data("mycolor")); }).on("mouseleave", ".buttons", function() { if (.$(this).is('.clicked')) { $(this),css("background-color"; ""). } }),on("click". ",buttons". function() { let isClicked = $(this).is(';clicked'). let x = $(this);css('background-color'). if (x == $(this).data("mycolor")) { $(this),css("background". $(this);data("mycolor")). } $(this),toggleClass('clicked'; ;isClicked). }). $("#done"),appendTo(gallery);on("click". clearColor). function clearColor() { $(".buttons"):removeClass('clicked');css({ backgroundColor: '' }); }
 .buttons { width: 150px; height: 50px; border: solid 2px black; text-align: center; color: black; cursor: pointer; background-color: white; margin: 2px; } #buttonGallery { margin: 10px; padding: 10px; border: solid 2px black; width: 155px; } #done { width: 150px; height: 50px; border: solid 2px black; text-align: center; color: black; cursor: pointer; background-color: white; margin: 2px; }
 <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="done"> <p>done</p> </div> <div id="buttonGallery"></div> </body> </html>

.map() returns an array. Have you tried to assign it to a variable?

buttons = myList.map(...)
<body>
<div id="buttonGallery"> <!-- add this line -->
  <div id="done">
    <p>done</p>
  </div>
</div> <!-- add this line -->
  <script type="text/javascript">
//    let $buttons = $('<div id="buttonGallery">'); <-- remove this line
    let $buttonGallery = $("#buttonGallery");
    let myList = ["A", "B", "C", "D"];
    let myColors = ["red", "green", "blue", "red"];

    $buttonGallery.children(":not(#done)").remove(); // <-- add this to remove added button except done button.

    myList.map(function(letter, index) {
      let $button = $("<div></div>")
        .addClass("buttons")
        .attr("id", "button_" + letter)
        .html("<p>" + letter + "</p>")
        .on("mouseenter", function() {
          $(this).css("background", myColors[index]);
        })
        .on("mouseleave", function() {
          if (!$(this).hasClass('clicked')) {
            $(this).css("background", "transparent");
          }
        })
        .on("click", function() {
          $(this).css("background", myColors[index]);
          $(this).addClass('clicked');
        })
      $("#done").before($button); // <-- edit this line
    });

    // $("body").append($buttons); <-- remove this line

    $("#done").on("click", clearColor);

    function clearColor() {
      $(".buttons").css({
        backgroundColor: 'transparent'
      });
      $(".buttons").removeClass('clicked');
    }
  </script>
</body>

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