[英]adding multiple event listeners ajax
I am trying to iterate an ajax query, yet whenever I try to run the code i always defaults to 1 I'm not very familiar with js and wondered whether anyone had any idea how to do this, or whether there is a better way to do it altogether.我正在尝试迭代 ajax 查询,但是每当我尝试运行代码时,我总是默认为1我对 js 不是很熟悉,想知道是否有人知道如何做到这一点,或者是否有更好的方法完全做到这一点。 Thanks in advance!
提前致谢!
$.each(Array(10), function(i) {
var clickedButton = $('#' + (++i));
$(clickedButton).click(function (){
$.ajax({
type: 'POST',
url: 'example.php',
data: {lightid: i},
success:function(result){}
});
});
});
You can achieve the desired result by using a data
attribute with the necessary data for each "button".您可以通过使用带有每个“按钮”所需数据的
data
属性来实现所需的结果。 This can be picked out via this.dataset.<attribute-name>
and sent to the server:这可以通过
this.dataset.<attribute-name>
挑选出来并发送到服务器:
$('[data-id]').on('click',function(){ $.post('https://jsonplaceholder.typicode.com/posts',{lightid:this.dataset.id}) .done(r=>console.log(r)) })
div[data-id] {cursor:pointer}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>Click on any div below:</div> <div data-id="1">one</div> <div data-id="2">two</div> <div data-id="3">three</div> <div data-id="4">four</div> <div data-id="5">five</div> <div data-id="6">six</div> <div data-id="7">seven</div> <div data-id="8">oneeight</div> <div data-id="9">nine</div> <div data-id="10">ten</div>
I used the attribute data-id
to hold the numerical information, as the html attribute id
should always have values starting with an alphabetical character.我使用属性
data-id
来保存数字信息,因为 html 属性id
应该始终具有以字母字符开头的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.