Kesalahan mengatakan saya kehilangan tanda kurung. Namun sintaksnya identik dengan w3Schools dan Mozilla. .css() berfungsi jika saya hanya menyetel satu gaya, tetapi rusak saat menyetel lebih dari 1.

JQuery

 <script>
      $(document).ready( function(){

          // event-handler to create new element
          function createContainer() {

              // variables store values from <select> element
              var elementType = $('select').val();

              // string containing markup for use with .append()
              var elementTypeStr = $(` <${elementType}> This is a ${elementType} </${elementType}> `);
              // this throws error, while setting single style doesn't
              $('#layout_demo').append( elementTypeStr );
              elementTypeStr.css("background-color":" blue" , "height": "100px");

          } // end createContainer()

          // ---------------------------- event handlers ---------------------

          $('#btn').click( createContainer );
          // button to delete latest element or selected element

      }); // end ready

  </script>

HTML:

<section id="form">
  <!-- select element --->
  <label for="container"> Please select type of container to add</label>
  <select id= "container">
    <option value= "div" > &ltdiv&gt </option>
    <option value= "p"> &ltp&gt </option>
    <option value= "section"> &ltsection&gt </option>

  </select>
  <!-- Seperate container to hold now elements -->

  <button id="btn" > Create Container </button>
</section>

<div id="layout_demo">



</div>
1
sebastian lavenant 30 Mei 2019, 23:55

1 menjawab

Beberapa properti .css() harus berada di dalam Object.

$(document).ready(function() {

  // event-handler to create new element
  function createContainer() {

    // variables store values from <select> element
    var elementType = $('select').val();

    // string containing markup for use with .append()
    var elementTypeStr = $(` <${elementType}> This is a ${elementType} </${elementType}> `);
    // this throws error, while setting single style doesn't
    $('#layout_demo').append(elementTypeStr);
    elementTypeStr.css({
      "background-color": " blue",
      "height": "100px"
    });

  } // end createContainer()

  // ---------------------------- event handlers ---------------------

  $('#btn').click(createContainer);
  // button to delete latest element or selected element

}); // end ready
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="form">
  <!-- select element --->
  <label for="container"> Please select type of container to add</label>
  <select id="container">
    <option value="div"> &ltdiv&gt </option>
    <option value="p"> &ltp&gt </option>
    <option value="section"> &ltsection&gt </option>

  </select>
  <!-- Seperate container to hold now elements -->

  <button id="btn"> Create Container </button>
</section>

<div id="layout_demo">



</div>
-1
OXiGEN 30 Mei 2019, 21:01