1

我有一个包含其他 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>
4

2 回答 2

5

删除转义的引号:

var myclass = "#container>div:not(."+mystring+")";
于 2012-11-19T19:37:02.663 回答
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​​​
于 2012-11-19T19:39:53.150 回答