首页 > 解决方案 > 如何使用带有值的 jQuery 更改 css 样式元素

问题描述

我正在制作一个程序,用户可以在其中选择要渲染的元素,还可以选择要添加到元素的 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>


标签: javascriptjquery

解决方案


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

$(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 );

});

推荐阅读