我一直在为我的小项目开发一项新功能,该功能从输入中获取命令(写入输入:制作一个名为 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'});
关于javascript - jQuery 未正确向元素添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51581331/