2015-07-10 72 views
0

我有一个JS的小问题。我想让JS用AJAX改变一些div的类。工作正常,直到它应该找到div。JavaScript不会改变div

function filter(cb){ 
 
\t \t var value = cb.value; 
 
\t \t if(cb.checked){ var state = "an" } 
 
\t \t if(!cb.checked){ var state = "aus" } 
 
\t \t var pstring = "Checkbox "+value+" = "+state; 
 
\t \t var url = "shownitems.php?checkbox="+value; 
 
\t \t $.get(url, 
 
\t \t \t { 
 
\t \t \t }, 
 
\t \t \t function(data){ 
 
\t \t \t \t var array = JSON.parse(data) 
 

 
\t \t \t \t if(cb.checked){ 
 
\t \t \t \t \t array.forEach(function(value, index, array) { 
 
         //alert(value) works fine for every index 
 
\t \t \t \t \t \t var divstring = value+"cont"; 
 
         //alert(divstring) gives correct id. div "1cont" exists! 
 
\t \t \t \t \t \t var div = document.getElementById(divstring); 
 
\t \t \t \t \t \t alert(div); //null 
 
\t \t \t \t \t }); 
 
\t \t \t \t } 
 
\t \t \t \t if(!cb.checked){ 
 
\t \t \t \t \t array.forEach(function(value, index, array) { 
 
\t \t \t \t \t \t var divstring = value+"cont"; 
 
\t \t \t \t \t \t var div = document.getElementById(divstring); 
 
\t \t \t \t \t \t alert(div); 
 
\t \t \t \t \t }); 
 
\t \t \t \t } 
 
\t \t \t \t \t \t 
 
\t \t \t } 
 
\t \t); 
 
\t }
我能做些什么?

+2

摆脱你的单位报价为div成员。 – colecmc

+0

不错的尝试,没有工作... –

+0

当我使用你的代码,我得到一个'语法错误,无法识别的表达式''''' – colecmc

回答

1

你必须删除单引号,因为你的选择会看起来像"'#foo'"

var div = "#" + value + "cont"; 
+0

试过了,没有工作:s –

+0

我建议稍微调试一下这个脚本,你需要确保$(div)不返回一个空数组。 – halfzebra

+0

document.getElementByID()给出null!查看新的片段;) –

0

这是我设置了添加和删除类,因为它涉及到你的问题存根:

function tryFunc1(value) { 
 
    /** 
 
    * @throws Uncaught Error: Syntax error, unrecognized expression: '' 
 
    */ 
 
    var div = "'#" + value + "cont'"; 
 
    $(div).removeClass('imgthumbbox'); 
 
    $(div).addClass('hidden'); 
 
    console.log($(div)); 
 
} 
 

 

 
function tryFunc2(value) { 
 
    /** 
 
    * @returns {array} 
 
    */ 
 
    var div = "#" + value + "cont"; 
 
    $(div).removeClass('imgthumbbox'); 
 
    $(div).addClass('hidden'); 
 
    console.log($(div)); 
 
} 
 

 

 
tryFunc2('colecmc'); 
 

 
tryFunc1('colecmc');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div id="colecmc" class="imgthumbbox">Hello</div>