javascript - jQuery 未正确向元素添加类

标签 javascript jquery

我一直在为我的小项目开发一项新功能,该功能从输入中获取命令(写入输入:制作一个名为 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/

相关文章:

javascript - 如何为通过java脚本动态创建的HTML表格行添加onclick事件?

javascript - 使用 jQuery 更改 HTML 字符串 : wont update the string

javascript - 如何通过回车和空格分割字符串

javascript - 结合 jQuery 准备 + 更改

javascript - dotenv 不适用于无服务器/webpack

jQuery 禁用启用链接事件处理程序

javascript - jQuery Mobile 中的最佳绑定(bind)时间

javascript - 在初始化时将所有过滤器选项设置为 'active' - Angular

javascript - 如何使用脚本调用函数

javascript - 与 javascript 中的 promise /链式函数有点混淆