jQuery无法将类正确添加到元素

时间:2018-07-29 14:31:07

标签: javascript jquery

我一直在为我的小项目开发一项新功能,该功能从输入中获取命令(写入输入:创建一个名为somename的框),如果它检测到该命令为“创建一个名为somename的框”,它将创建一个somename类的div。但是,当我尝试向#include <string> #include <sstream> void loginToWebsite(const std::string &url, const std::string &userAgent, const std::string &username, const std::string &password) { CURL *curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str()); curl_easy_setopt(curl, CURLOPT_POST, 1L); std::ostringstream oss; oss << "j_username="; char *encoded = curl_easy_escape(curl, username.c_str(), username.length()); if (encoded) { oss << encoded; curl_free(encoded); } oss << "&j_password="; encoded = curl_easy_escape(curl, password.c_str(), password.length()); if (encoded) { oss << encoded; curl_free(encoded); } std::string postdata = oss.str(); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L); curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt"); CURLcode res = curl_easy_perform(curl); // use res as needed... curl_easy_cleanup(curl); } } 元素添加样式时,什么也没发生。问题出在switch语句的div

上方的行中

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('');
  }
});

3 个答案:

答案 0 :(得分:1)

您应该使用jquery的css()方法而不是那里的addClass,使用与

相同的语法。
$('.'.concat(name)).css({'background-color': 'green', 'height': '50px', 'width': '50px'});

答案 1 :(得分:1)

似乎您尝试使用错误的方法。尝试使用css代替addClass

.addClass({'background-color': 'green', 'height': '50px', 'width': '50px'});

必须是

.css({'background-color': 'green', 'height': '50px', 'width': '50px'});

答案 2 :(得分:1)

为更加清楚起见,不能使用.addClas()方法的原因是因为“ background-color”不是类,而是css属性。因此,您必须使用.css()方法进行设置。

.css({'background-color': 'green', 'height': '50px', 'width': '50px'});