简体   繁体   中英

How to find next element in jQuery?

How to find next element in jquery, i have following code

<div>
 <input id="btn<%# Eval("Id") %>" type="button" value="fetch"/>
</div>
<div>
 <img id="imgLoading<%# Eval("Id") %>" style="width: 200px;height: 10px; display: none" src="/Images/Loading.gif" />
</div>
<div id="divData<%# Eval("Id") %>"></div>

NOTE : here my "imgLoading[Binding ID]" and divData[bindingID] here, so everytime my id is not same , they are different in every items

what i am doing is , when you click on button, image will show ( image is gif to show the loading started) and i called $ajax -webmethod to load data in div , when data loaded, i will hide image

i want to hide image when we click on button and append data in div elements

thanks in advance

Try this:

$("input[type=button]").click(function() {
    var img = $(this).closest("#imgLoading").show();
    var div = $(this).closest("#divData");

    $.ajax({
      url: ...
      success: function(data) {
        $(img).hide();
        $(div).html(data);
      }
    });
});

You can also use starts with selector( doc ).

$('input[id^=btn]').click(...)
$("input[type='button']").click(function () {
    $(this).closest('div').next('div');    // next div., containing the img 
                                           // element with id imgLoading....
})

Use appropriate id/class/attribute/tag selector as you see appropriate.

Live JSFiddle Demo .

Maybe you can try something like this -

<div>
    <input id="btn<%# Eval("Id") %>" type="button" value="fetch"/>
</div>
<script type="text/javascript">
    $(document).ready( function () {
        $('input#btn<%# Eval("Id") %>').click(function () {
            var nextDiv = $(this).closest('div').next('div');

            // do whatever you want with this div here
        }); 
    });
</script>
<div>
     <img id="imgLoading<%# Eval("Id") %>" style="width: 200px;height: 10px; display: none" src="/Images/Loading.gif" />
</div>
<div id="divData<%# Eval("Id") %>"></div>

I must admit the above code is ugly. If you don't want to mix JS code with html, you can move this code out to some external JS file, but then you need to ensure a specific ID to the input type="button" element.

What you would need to do is use jQuery's next() function -

$('input[type="button"]').on('click',function(){
  var imgLoadingElement = $(this).parent().next('div').find('img');
  var divDataElement = imgLoadingElement.parent().next('div[id^="divData"]');
});

Try

$(document).ready(function(){
 $('yourButtonSelector').click(function(){
   $(this).parent().next().find('yourImageSelector');//.doaction
   //or
   $(this).closest('yourImageSelector');//.doaction
 });

 });

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