在 jquery 中每次单击后使用 while 循环进行更改
use while loop for change after every click in jquery
我想在点击事件后改变一些东西,但我需要使用 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,等等
使用固定前缀运算符创建事件。这里 div[id^=DIV] 分配点击事件以添加具有前缀 'DIV' 的 ID 的 div 元素。 $(this).index() return 该元素在一组 div 中的索引 whit id 与 'DIV'
统计
$('div[id^=DIV]').click(function() {
// DoSomething
ExapmleVar = ($(this).index() + 1);
}
使用id starting with
选择器
$('div[id^=DIV]').click(function() {
或
$('className').click(function() {
在这种情况下循环是不好的做法,您可以使用 class 代替,
$('.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>
我想在点击事件后改变一些东西,但我需要使用 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,等等
使用固定前缀运算符创建事件。这里 div[id^=DIV] 分配点击事件以添加具有前缀 'DIV' 的 ID 的 div 元素。 $(this).index() return 该元素在一组 div 中的索引 whit id 与 'DIV'
统计 $('div[id^=DIV]').click(function() {
// DoSomething
ExapmleVar = ($(this).index() + 1);
}
使用id starting with
选择器
$('div[id^=DIV]').click(function() {
或
$('className').click(function() {
在这种情况下循环是不好的做法,您可以使用 class 代替,
$('.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>