简体   繁体   English

如何多次调用具有相同Div的Ajax

[英]How to Call Ajax With Same Div Multiple Times

I am calling ajax with below code in my index.php file. 我在index.php文件中使用以下代码调用ajax。

<script type="text/javascript">
    $(document).ready(function(){
        $("#counting").click(function(){
            $.ajax({
                type: 'POST',
                url: 'https://example.com/update.php',
                data: {url: '<?=$url?>'},
                success: function(data) {
                   // alert(data);
                    //$("p").text(data);

                }
            });
   });
});
</script>

It's working perfectly, but the issue is I have div called counting multiple times on the page. 它工作正常,但是问题是我在页面上多次调用div进行计数。 example

 <div id="counting">
<a href="example.com">example</a>
</div>

 <div id="counting">
<a href="example.com">example</a>
</div>

Issue - Ajax call only works with first div, not below divs. 问题-Ajax调用仅适用于第一个div,而不适用于div以下。 How to make it work with all divs with id counting 如何使其与所有具有ID计数的div一起使用

Id attributes are supposed to be unique. id属性应该是唯一的。 You're only ever going to get the first div called because once the DOM sees that, it's met it's requirement and doesn't search further. 您只会调用第一个div,因为一旦DOM看到了它,就满足了它的要求,并且不再进行进一步的搜索。 I suggest you give you divs unique ids and then use a class that is the same for all of them. 我建议您为divs提供唯一的ID,然后对所有这些ID使用相同的类。

 <div id="div1" class="counting_class">
<a href="example.com">example</a>
</div>

<div id="div2" class="counting_class">
<a href="example.com">example</a>
</div>

Then your jQuery would look something like this: 然后您的jQuery将如下所示:

$(".counting_class").click(function(){
  var id = $(this).attr('id');
//then call ajax based on the individual ID
}

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

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