错误提示我缺少括号。但是语法与 w3Schools 和 Mozilla 相同。 .css() 在我只设置一种样式时有效,但在设置超过 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" > <div> </option>
<option value= "p"> <p> </option>
<option value= "section"> <section> </option>
</select>
<!-- Seperate container to hold now elements -->
<button id="btn" > Create Container </button>
</section>
<div id="layout_demo">
</div>
最佳答案
使用 .css()
时,您有两种传递参数的选择:逗号分隔的字符串或对象文字表示法
因此:
.css("background-color", " blue").css("height", "100px");
或者更确切地说:
.css({backgroundColor:"blue" , height:"100px"});
此外,不要使用 $('select').val();
使用更严格的选择器,例如某些 ID; 'select'
可以是您页面中的任何选择。
jQuery($ => {
const createElement = () => {
const tagName = $('#element').val();
return $(`<${tagName}/>`, {
appendTo: '#layout',
text: `This is a ${tagName}`,
css: {
backgroundColor: "blue",
height: "100px"
},
});
}
$('#create').on('click', createElement);
});
<section id="form">
<label>
Please select type of container to add
<select id="element">
<option value="div"><div></option>
<option value="p"><p></option>
<option value="section"><section></option>
</select>
</label>
<button id="create">Create Container</button>
</section>
<div id="layout"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
关于javascript - 对 iQuery 方法 .css() 使用多个值会抛出错误 : 'missing )' . 但是它不会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56385508/