簡體   English   中英

jQuery無法將類正確添加到元素

[英]jQuery not adding class to element properly

我一直在為我的小項目開發一項新功能,該功能從輸入中獲取命令(寫入輸入:創建一個名為somename的框),如果它檢測到該命令為“創建一個名為somename的框”,它將創建具有somename類的div。 但是,當我嘗試向div元素添加樣式時,什么也沒發生。 問題出在switch語句的break;上方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'});

似乎您嘗試使用錯誤的方法。 嘗試使用css而不是addClass

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

它一定要是

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

為了更加清楚,您不能使用.addClas()方法的原因是因為“ background-color”不是類,而是css屬性。 因此,您必須使用.css()方法進行設置。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM