我有一个包含其他div(很多类)的div(id = container) 我能够将容器用作字符串“AAAA”但不能用变量mystring做同样的效果
<div id="container">
<div class="AAAA">AAAA content</div>
<div class="AAAA">AAAA content</div>
<div class="BBBB">BBBB content</div>
<div class="CCCC">CCCC content</div>
<div class="DDDD">DDDD content</div>
<div class="AAAA">AAAA content</div>
</div>
<script>
var myclass = "#container>div:not("+".AAAA"+")"; // works
$(myclass).css("background-color", "red"); //works fine
//var mystring = "AAAA";
//var myclass = "\"#container>div:not(."+mystring+")\"";
//$(myclass).css("background-color", "red"); // doesn't work
</script>
答案 0 :(得分:5)
删除转义的引号:
var myclass = "#container>div:not(."+mystring+")";
答案 1 :(得分:1)
工作演示 http://jsfiddle.net/xWWcZ/
原因:您不需要转义\#
哈希。
希望休息符合原因。
<强>代码强>
//var myclass = "#container>div:not("+".AAAA"+")"; // works
//$(myclass).css("background-color", "red"); //works fine
var mystring = "AAAA";
var myclass = "#container>div:not(."+mystring+")";
$(myclass).css("background-color", "red"); // work now