如何使用jQuery和<input />元素中的值更改CSS样式

时间:2019-05-24 19:12:53

标签: javascript jquery

我正在编写一个程序,用户可以在其中选择要渲染的元素,还可以选择CSS样式添加到该元素。

程序成功呈现未更改的元素。困难在于改变样式。到目前为止,我只是更改宽度和高度。 !我不会使用.width()/。height()方法,因为我想包含单位并更改其他CSS属性。

我收到此错误:未捕获的TypeError:latestElement.css不是函数

这告诉我.css()似乎不适用于jQuery原型。

 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>

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

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


<div id="layout_demo">

</div>

```

为避免为每个已知元素分配新的id属性,我使用每个元素的列表(即$('element')[i])进行选择。我将该引用存储在变量中,但它会破坏.css()。

      <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous"></script>

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

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

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

        // string containing markup for use with .append()
        var elementTypeStr = "<" + elementType + "> This is a " + elementType + 
                              "</" + elementType + ">" ;

            $('#layout_demo').append( elementTypeStr );
            // create jQuery prototype for prototype.css()
             i = $( elementType ).length;
               latestElement = $(elementType)[i - 1];
            latestElement.css( "width", function(){
                return width + widthUnit ;
            });

        } // end createContainer()

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

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

    }); // end ready

  </script>


1 个答案:

答案 0 :(得分:1)

无需获取最后一项,请这样做:-

$(document).ready( function(){

  function createContainer() {
    var selector = $('select');
    var el = $('select').val();
    var elementType = $(`<${el}> This is ${el} </${el}>`) ;
    $('#layout_demo').append( elementType );
    elementType.css( "border", '1px solid red');
  }
  $('#btn').click( createContainer );

});