我有以下代码:
<script>
var Var1 = "";
$(document).ready(function() {
window.Var1 = "Easy";
});
</script>
<script>
$(document).ready(function() {
if $("div."+window.Var1).length > 0){
alert("success"); //DOESN'T WORK
}
});
</script>
这不会提醒&#34;成功&#34;
如果我将window.Var1
替换为Easy
(如下所示),则警报有效;因此,条件得到满足,但代码并未将$("div."+window.Var1)
解释为$("div.Easy")
<script>
var Var1 = "";
$(document).ready(function() {
window.Var1 = "Easy";
});
</script>
<script>
$(document).ready(function() {
if $("div.Easy").length > 0){
alert("success"); // WORKS
}
});
</script>
答案 0 :(得分:1)
您的问题在这一行:
if $("div."+window.Var1).length > 0){
将其更改为:
if ($("div."+window.Var1).length > 0){
^
你忘记了左括号:
var Var1 = "";
$(document).ready(function() {
window.Var1 = "Easy";
});
$(document).ready(function() {
if ($("div."+window.Var1).length > 0){
console.log("success"); //DOESN'T WORK
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Easy">.....</div>