简体   繁体   English

我如何使用jQuery更改与类条件匹配的直接img兄弟元素的CSS

[英]How do I use jQuery to change the CSS of direct img sibling elements matching a class conditional

I am trying to make a set of greyed out images switch with color images when a checkbox is checked within a table row. 当表格行中的复选框被选中时,我试图使一组带有灰色图像的灰色图像切换。 This operation will be reversed when the checkbox is unchecked again. 再次取消选中该复选框时,此操作将相反。 The changes must only apply to img elements in that particular tablerow. 所做的更改必须仅适用于该特定表行中的img元素。 The table rows will be dynamically generated but will follow this DOM structure. 表行将动态生成,但将遵循此DOM结构。 I have looked into .parent() .parentAll() but these do not seem to provide the matches. 我已经研究了.parent().parentAll(),但是这些似乎没有提供匹配项。 I am happy to apply non jQuery javascript if it is not possible in jQuery but I would prefer to use jQuery if possible 如果无法在jQuery中使用非jQuery JavaScript,我很乐意,但我希望尽可能使用jQuery

<html>

  <head>
      <meta charset="utf-8">
       <title> Total Tutor </title>
        <link type="text/css" rel="stylesheet" href="course.css"> 
          <script src="../jquery.js"></script> 

    <style>
       .color{display:none;}
       .grey{display:block;}  
    </style>

  </head>   

 <body>

  <div>  
   <form>
    <table id="units" >

     <thead> 
       <tr>
        <th>Units</th> 
            <th>Add Video</th>
            <th>Add Worksheet</th>
            <th>Add Quiz</th>
            <th>Add Exam</th>
            <th>Add Revision</th>
        </tr>  
      </thead>

      <tbody>

       <!--  table rows will be dynamically generated based on a SQL query -->
        <tr>
            <td class="unit_table"><input type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 2.1.1.1</td>
            <td class="unit_table"><img class="color" src="../images/video-selector-small.png"><img class="grey" disabled src="../images/video-selector-small-grey.png"></td>      
            <td class="unit_table"><img class="color" src="../images/worksheet-selector-small.png"><img class="grey" disabled src="../images/worksheet-selector-small-grey.png"></td>    
        </tr>

        <tr>
            <td class="unit_table"><input type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 3.1.1.1</td>
            <td class="unit_table"><img class="color" src="../images/video-selector-small.png"><img class="grey" disabled src="../images/video-selector-small-grey.png"></td>      
            <td class="unit_table"><img class="color" src="../images/worksheet-selector-small.png"><img class="grey" disabled src="../images/worksheet-selector-small-grey.png"></td>    
        </tr>

      </tbody>
    </table> 

    <button type="submit" id="save_design_course" name="sent" value="save_design_course"><img src="../images/save.png"></button>

  </form>
 </div>
 </body>
</html>  

<script>

  $(document).ready(function() 
    {
     $(".design_units").click(function ()
      {
       if ($(this).is(':checked')) 
        {
          /*change all of the img elements of class grey to display: none 
          and change all img elements of class color to display:block*/
        } 

       if (!$(this).is(':checked')) 
        {
          /*change all of the img elements of class grey to display:block 
          and change all img elements of class color to display:none*/
        } 
      });    
</script> 

You have lot of syntax errors in the script block. 您在脚本块中有很多语法错误。

You can use closest() and find tr and access the color and grey classes 您可以使用closest()并找到tr并访问颜色和灰色类

 $(document).ready(function(){
     $(".design_units").on('click',function(){
       if ($(this).is(':checked')) {
          /*change all of the img elements of class grey to display: none 
          and change all img elements of class color to display:block*/
          $(this).closest('tr').find('.color').show();
          $(this).closest('tr').find('.grey').hide();          
        } 

       if (!$(this).is(':checked')){
          /*change all of the img elements of class grey to display:block 
          and change all img elements of class color to display:none*/
          $(this).closest('tr').find('.color').hide();
          $(this).closest('tr').find('.grey').show();
        } 
      });  
   });
  1. If it is gonna generate dynamically use on as 如果要生成动态地使用

$("body").on("change", ".design_units", function(){ //Your code });

You can use other selector instead of "body", if that is present on page while event binding. 如果事件绑定时页面上存在该选择器,则可以使用其他选择器代替“ body”。

  1. Use find and closest to find the exact elements in your case. 使用find最接近来找到您所需要的确切元素。 for eg. 例如 - --

    $(this).closest('tr').find('.grey').hide();

another simple way to show and hide your image, is using toggle() rather than checking its checked property 显示和隐藏图像的另一种简单方法是使用toggle()而不是检查其checked属性

toggle() is used to switch the visibility of elements from hide to show , vice versa. toggle()用于将元素的可见性从hide切换到show ,反之亦然。

$(".design_units").click(function ()
{
  $(this).parents('tr').find('img.grey').toggle();
  $(this).parents('tr').find('img.color').toggle();
}); 

demo : https://jsfiddle.net/81sLL212/ 演示: https : //jsfiddle.net/81sLL212/

Within the click handler (or you could use a change handler, but either is OK for checkboxes) you can find the clicked element's associated images by using .closest("tr") to navigate up to the containing row, then .find("img") to navigate back down to the images in that row. click处理器(或者你可以使用一个change的处理程序,但无论是对OK复选框),你可以找到点击的元素的相关图像通过使用.closest("tr")最多浏览到包含行,然后.find("img")向下导航到该行中的图像。

Then you can call .toggle() on those images, passing a boolean argument to indicate whether to show or hide each one. 然后,您可以在这些图像上调用.toggle()并传递一个布尔参数来指示是显示还是隐藏每个图像。

This means you don't need an if/else structure and the event handler can be reduced to three lines: 这意味着您不需要if/else结构,事件处理程序可以简化为三行:

 $(document).ready(function() { $(".design_units").click(function() { // When a CB is clicked var imgs = $(this).closest("tr").find("img"); // find its associated imgs imgs.filter(".color").toggle(this.checked); // Show color if CB checked imgs.filter(".grey").toggle(!this.checked); // Show grey if CB not checked }); }); 
 .color { display: none; } .grey { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id="units"> <tbody> <tr> <td class="unit_table"><input type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 2.1.1.1</td> <td class="unit_table"><img class="color" alt="color" src="../images/video-selector-small.png"><img class="grey" alt="grey" disabled src="../images/video-selector-small-grey.png"></td> <td class="unit_table"><img class="color" alt="color" src="../images/worksheet-selector-small.png"><img class="grey" alt="grey" disabled src="../images/worksheet-selector-small-grey.png"></td> </tr> <tr> <td class="unit_table"><input type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 3.1.1.1</td> <td class="unit_table"><img class="color" alt="color" src="../images/video-selector-small.png"><img class="grey" alt="grey" disabled src="../images/video-selector-small-grey.png"></td> <td class="unit_table"><img class="color" alt="color" src="../images/worksheet-selector-small.png"><img class="grey" alt="grey" disabled src="../images/worksheet-selector-small-grey.png"></td> </tr> </tbody> </table> 

Note that when dealing with a single checkbox this.checked gives you the same boolean value as $(this).is(':checked') , except it is easier to read, faster to type, and faster to execute. 请注意,在处理单个复选框时, this.checked$(this).is(':checked')拥有相同的布尔值,但它更易于阅读,键入更快,执行更快。

(Note: in the demo above I've given the images an alt attribute so that you can tell whether they're the .color or .grey ones without needing valid src paths.) (注意:在上面的演示中,我为图像提供了alt属性,以便您无需使用有效的src路径即可知道它们是.color还是.grey 。)

EDIT: If the table is dynamically generated in the sense of being loaded via Ajax after the initial page load then replace the following line: 编辑:如果在初始页面加载后就通过Ajax加载的意义上说,动态生成了该表,则替换以下行:

$(".design_units").click(function() {

...with: ...具有:

$(document).on("click", ".design_units", function() {

Where ideally document would be replaced by the nearest parent element that is static. 理想情况下, document将被最接近的静态父元素替换。

You can use closest() to get the nearest ancestor with a particular tag, then find() to get all children matching a jQuery selector under that ancestor. 您可以使用closest()获取具有特定标签的最接近的祖先,然后使用find()获取与该祖先下的jQuery选择器匹配的所有子代。

I switched the images for buttons because we don't have access to the actual images, and closed the document.ready() function: 由于无法访问实际图像,所以我将图像切换为按钮,并关闭了document.ready()函数:

  $(document).ready(function() { $(".design_units").click(function () { if ($(this).is(':checked')) { $(this).closest('tr').find('.grey').hide(); $(this).closest('tr').find('.color').show(); } if (!$(this).is(':checked')) { $(this).closest('tr').find('.grey').show(); $(this).closest('tr').find('.color').hide(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <meta charset="utf-8"> <title> Total Tutor </title> <link type="text/css" rel="stylesheet" href="course.css"> <script src="../jquery.js"></script> <style> .color{display:none;} .grey{display:block;} </style> </head> <body> <div> <form> <table id="units" > <thead> <tr> <th>Units</th> <th>Add Video</th> <th>Add Worksheet</th> <th>Add Quiz</th> <th>Add Exam</th> <th>Add Revision</th> </tr> </thead> <tbody> <!-- table rows will be dynamically generated based on a SQL query --> <tr> <td class="unit_table"><input type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 2.1.1.1</td> <td class="unit_table"><button class="color" src="../images/video-selector-small.png"><button class="grey" disabled src="../images/video-selector-small-grey.png"></td> <td class="unit_table"><button class="color" src="../images/worksheet-selector-small.png"><button class="grey" disabled src="../images/worksheet-selector-small-grey.png"></td> </tr> <tr> <td class="unit_table"><input type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 3.1.1.1</td> <td class="unit_table"><button class="color" src="../images/video-selector-small.png"><button class="grey" disabled src="../images/video-selector-small-grey.png"></td> <td class="unit_table"><button class="color" src="../images/worksheet-selector-small.png"><button class="grey" disabled src="../images/worksheet-selector-small-grey.png"></td> </tr> </tbody> </table> <button type="submit" id="save_design_course" name="sent" value="save_design_course"><img src="../images/save.png"></button> </form> </div> </body> </html> 

You might use the .parents() selector to get the appropriate table row, then search for the image you want within that row. 您可以使用.parents()选择器获取适当的表格行,然后在该行中搜索所需的图像。 Here's an example solution to your problem following that pattern: 这是遵循该模式的问题的示例解决方案:

$('.design-units').on('change', (e)=>{
  const $row = $(e.target).parents('tr');
  const $grays = $row.find('.grey');
  const $colors = $row.find('.color');

  const isChecked = $(e.target).is(':checked');

  if(isChecked){
    $grays.attr('disabled', false);
    $colors.attr('disabled', true);
  } else {
    $grays.attr('disabled', true);
    $colors.attr('disabled', false);
  }
})

You need to iterate through each img as 您需要迭代每个img

$(document).ready(function() 
    {
     $(".design_units").click(function ()
      {
       if ($(this).is(':checked')) 
        {
         $(this).parent().nextAll('td').find('img').each(function(){
          if($(this).attr('class') == 'color')
          {
            $(this).css('display','block');
          }else if($(this).attr('class') == 'grey')
          {
            $(this).css('display','none');
          }
         })
          /*change all of the img elements of class grey to display: none 
          and change all img elements of class color to display:block*/
        } 

       if (!$(this).is(':checked')) 
        {
        $(this).parent().nextAll('td').find('img').each(function(){
          if($(this).attr('class') == 'grey')
          {
            $(this).css('display','block');
          }else if($(this).attr('class') == 'color')
          {
            $(this).css('display','none');
          }
         })
          /*change all of the img elements of class grey to display:block 
          and change all img elements of class color to display:none*/
        } 
      });   
      });

Working fiddle : https://jsfiddle.net/gaq23jbL/3/ 工作提琴: https : //jsfiddle.net/gaq23jbL/3/

try this, 尝试这个,

    <html>
    <hrad></head>
    <body>
    <div>  
           <form>
            <table id="units" >

             <thead> 
               <tr>
                <th>Units</th> 
                    <th>Add Video</th>
                    <th>Add Worksheet</th>
                    <th>Add Quiz</th>
                    <th>Add Exam</th>
                    <th>Add Revision</th>
                </tr>  
              </thead>

              <tbody>

               <!--  table rows will be dynamically generated based on a SQL query -->
                <tr>
                    <td class="unit_table"><input type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 2.1.1.1</td>
                    <td class="unit_table"><img alt="color" class="color" src="../images/video-selector-small.png"><img alt="grey" class="grey" disabled src="../images/video-selector-small-grey.png"></td>      
                    <td class="unit_table"><img class="color" src="../images/worksheet-selector-small.png"><img class="grey" disabled src="../images/worksheet-selector-small-grey.png"></td>    
                </tr>

                <tr>
                    <td class="unit_table"><input  type="checkbox" class="design_units" name="units[]" value="Bike"> Unit 3.1.1.1</td>
                    <td class="unit_table"><img class="color" src="../images/video-selector-small.png"><img class="grey" disabled src="../images/video-selector-small-grey.png"></td>      
                    <td class="unit_table"><img class="color" src="../images/worksheet-selector-small.png"><img class="grey" disabled src="../images/worksheet-selector-small-grey.png"></td>    
                </tr>

              </tbody>
            </table> 

            <button type="submit" id="save_design_course" name="sent" value="save_design_course"><img src="../images/save.png"></button>

          </form>
         </div>


        <script>
            $(function(){
          $('#units').on('click','.design_units',function ()
      {
       if ($(this).is(':checked')) 
        {
            $($(this).closest('tr').find('.grey')).hide();
          $($(this).closest('tr').find('.color')).show();
          /*change all of the img elements of class grey to display: none 
          and change all img elements of class color to display:block*/
        } 

       if (!$(this).is(':checked')) 
        {
        $($(this).closest('tr').find('.grey')).show();
          $($(this).closest('tr').find('.color')).hide();
          /*change all of the img elements of class grey to display:block 
          and change all img elements of class color to display:none*/
        } 
 });
        });
        </script>
    </body>
    </html>

js-fiddle js小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM