我正在编写一个程序,用户可以在其中选择要渲染的元素,还可以选择CSS样式添加到该元素。
程序成功呈现未更改的元素。困难在于改变样式。到目前为止,我只是更改宽度和高度。 !我不会使用.width()/。height()方法,因为我想包含单位并更改其他CSS属性。
我收到此错误:未捕获的TypeError:latestElement.css不是函数
HTML:
```
<section id="form">
<!-- select element --->
<label for="container"> Please select type of container to add</label>
<select id= "container">
<option value= "div" > <div> </option>
<option value= "p"> <p> </option>
<option value= "section"> <section> </option>
</select>
<button id="btn" > Create Container </button>
</section>
<!-- Seperate container to hold now elements -->
<div id="layout_demo">
</div>
```
<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>
答案 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 );
});