简体   繁体   中英

jquery-Get the id of closest div?

Hi I have a Table with list of vehicle

 <table>
 <tr class="${(i % 2) == 0 ? 'odd' : 'even'}" id ="rows">
   <td>
      <div class="check_box_div">
       <div class="check_box_list">
         <g:checkBox id = "isActive_${i}" class="isActive" name="isActive"  value="${vehicleInstance?.isActive}" />
          <input type="hidden" value="${vehicleInstance?.id}" class="vehicleId" name="vehicleId" id="isActive_${i}_" />
        </div>
       <div class="display_image" id ="display_image_${i}"></div>
      </div>    
    </td>

  </tr>

table has got many rows I want to get the id of div where the class name is " display_image " for each row i tried to get it like

   $(".isActive").click(function() {
     var checkBox_id = $(this).attr("id");
     var checkbox = $('#'+checkBox_id);
     var div_id =$('#'+checkBox_id).closest("div").find(".display_image").attr("id"); // always returns div_id =display_image_0(div id of first row)

This is works for first row but for second row also it returns id of div of first row only what is the change i should make so that i will get the id of div on each row

Go up until you find the row, and then down again to find the display image:

$(".isActive").click(function() {
    var div_id = $(this).closest('tr').find('.display_image').attr(id);
    // ...
});

Note that this doesn't depend on your original element's ID at all - just the layout of your elements within the DOM.

More optimal solutions are possible, but this one will work regardless of the relative positions of the .isActive and .display_image elements within each row.

Try this.

 $(".isActive").click(function() {
 var div_id = $(this).parents(".check_box_list").next(".display_image").attr("id");
 }

I used parents rather than parent just in case you shift any of your markup around.

closet will not work here..as much as i know closet works towards parent heirarachy.

try this one

var div_id =$('#'+checkBox_id).parents(".check_box_div").find(".display_image").attr("id"); 

Use

$(".isActive").click(function() {
    var $row = $(this).closest("tr");
    var $div_id = $row.find("div.display_image").attr("id");
});

jsFiddle: http://jsfiddle.net/5TV9A/8/

You can store all the info in an Array and handle them after the loop.

$(".isActive").click(function() {
     var checkBox_id = $(this).attr("id");
     var checkbox = $('#'+checkBox_id);
     var div_array = new Array();
     $('.display_image').each(function(index) {
              var div_array[index] = //whatever you want;
      });
     // Now in div_array you have stored all the information you want (the id as well)

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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