我想在点击事件后改变一些事情,但我需要使用while循环来制作短代码。
例如:
$('#DIV1').click(function() {
// DoSomething
}
$('#DIV2').click(function() {
// DoSomething
}
使用while循环
var i = 1; var ExapmleVar
while(i < 5)
{
$('#DIV' + i).click(function() {
ExapmleVar = i;
}
}
在结果ExapmleVar = 6中,对我来说不是这样,我希望ExampleVar在第一个循环中等于1,在第二个循环中等于2等等
答案 0 :(得分:2)
使用修复前缀运算符创建事件。这里div [id ^ = DIV]指定click事件以添加id为前缀&#39; DIV&#39;的div元素。 $(this).index()返回一组div中该元素的索引.white id为stat with&#39; DIV&#39;
$('div[id^=DIV]').click(function() {
// DoSomething
ExapmleVar = ($(this).index() + 1);
}
答案 1 :(得分:0)
使用id starting with
选择器
$('div[id^=DIV]').click(function() {
或
$('className').click(function() {
答案 2 :(得分:0)
在这种情况下循环是不好的做法,你可以使用类来代替,
$('.common-class').click(function(){
ExapmleVar = $('.common-class').index(this)+1;
});
$('.common-class').click(function(){
alert($('.common-class').index(this)+1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="common-class">1</div>
<div class="common-class">2</div>
<div class="common-class">3</div>
<div class="">Not common. Yeah!</div>
<div class="common-class">4</div>