2017-07-02 61 views
1

我的js函數幾乎可以工作,但複選框不能獨立工作:複選框不能獨立工作

更新:我通過添加parent ='NULL'修復了這個問題;在函數結束時。有人可以解釋發生了什麼?

function detectDiv(obj) { 
 
    var parent = obj.parentElement; 
 
    console.log(parent.id); 
 
    
 
    
 
    $('input:checkbox').change(function(){ 
 
    if($(this).is(":checked")) { 
 
     $("#"+parent.id).removeClass("grey100"); 
 
    } else {  $("#"+parent.id).addClass("grey100"); 
 
    } 
 

 
    parent='NULL'; 
 
}); 
 

 
    
 
    
 
    
 
    
 
}
.grey100 { 
 
    
 
      opacity: 0.5; 
 
} 
 

 
img{ 
 
width:100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div > 
 
<table> 
 
    <tr> 
 
     <td id='img1' class='grey100'> 
 
<img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br> 
 
<input type="checkbox" onclick="detectDiv(this)" > 
 
     </td> 
 
     <td id='img2' class='grey100'> 
 
<img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br> 
 
<input type="checkbox" onclick="detectDiv(this)" > 
 
     </td> 
 
     </tr> 
 
</table> 
 
</div>

回答

3

我不明白這一點使用一個單獨的函數嵌套jQuery函數來處理它。

$('input:checkbox').change(function() { 
 
    $(this).parent().find('img').toggleClass("grey100"); 
 
});
.grey100 { 
 
    opacity: 0.5; 
 
} 
 

 
img { 
 
    width: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div> 
 
    <table> 
 
    <tr> 
 
     <td id='img1'> 
 
     <img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br> 
 
     <input type="checkbox"> 
 
     </td> 
 
     <td id='img2'> 
 
     <img src="https://res.cloudinary.com/rss81/image/upload/gw.jpg"><br> 
 
     <input type="checkbox"> 
 
     </td> 
 
    </tr> 
 
    </table> 
 
</div>

:您可以通過以下方式獲得您預期的結果