我一直在为我的小项目开发一项新功能,该功能从输入中获取命令(写入输入:创建一个名为somename的框),如果它检测到该命令为“创建一个名为somename的框”,它将创建具有somename类的div。但是,当我尝试向div
元素添加样式时,什么也没有发生。问题出在switch语句的break;
上方的行中
// checks if word is in string s
function wordInString(s, word){
return new RegExp( '\\b' + word + '\\b', 'i').test(s);
}
$('input').keypress(function(e) {
if (e.which == 13) {
let input = $(this).val();
console.log("Initial Input: " + input);
const Commands = ['call it', 'name it', 'make a box called'];
split_input = input.split(" ");
var arrayLength = Commands.length;
for (var i = 0; i < arrayLength; i++) {
command = Commands[i];
console.log(command);
let wordFound = wordInString(input, command);
if (wordFound) {
console.log("Command found: " + command)
switch (command) {
case "make a box called":
let name = split_input[4];
console.log("Box name: " + name)
$('.Dragon').append($('<div>', {class: name}));
// this is the problem line, I do not quite get why it won't w ork
$('.'.concat(name)).addClass({'background-color': 'green', 'height': '50px', 'width': '50px'});
break;
default:
}
}
}
$(this).val('');
}
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- Dependencies -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" charset="utf-8"></script>
<title>CodeDragon</title>
<link rel="stylesheet" href="/master.css">
</head>
<body>
<div class="Dragon"></div>
<input type="text" name="_input" value="">
<script src="script.js" charset="utf-8"></script>
</body>
</html>
最佳答案
您应该使用jquery的css()方法而不是那里的addClass,使用与以下相同的语法:
$('.'.concat(name)).css({'background-color': 'green', 'height': '50px', 'width': '50px'});