javascript - 如何使用带有值的 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" > <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>
```
为了避免为每个已知元素分配新的 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>
解决方案
无需获取最后一项,这样做:-
$(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 );
});
推荐阅读
- postgresql - 在交叉点 Postgresql 后排序数据
- angular - 将对象数组值与其他对象值映射
- bash - 运行 smem 命令时,如何让 bash 打印没有大小为零的字段的输出?
- docker - 有没有办法在不构建的情况下将 docker-compose 容器无缝传输到另一台主机?
- javascript - 如何从平面标准化的对象数组中生成平面的祖先数组?
- python-3.x - Python - 猴子补丁失败,为什么?
- sql-server - linux 上的 MSSQL 2017:CU14 上的 Windows 身份验证被破坏
- informatica - 使用 informatica powercenter 到关系数据库的 Web 服务提供程序
- php - 如何使用 PHP 将 SQL Server 表中新添加的行传输到相同的 MySQL 表?
- dax - 如何找到一列中的值比另一列中的值大多少倍?