英文:
Same function with different numbers
问题
example 1:
$("#O1").click(function() {
KSlevel = 1;
alert(KSlevel);
$('#ks' + KSlevel).fadeIn(200);
});
$("#O2").click(function() {
KSlevel = 2;
alert(KSlevel);
$('#ks' + KSlevel).fadeIn(200);
});
example 2:
$("#OX").click(function() {
KSlevel = X;
alert(KSlevel);
$('#ks' + KSlevel).fadeIn(200);
});
英文:
who can help me?
I have 30 buttons if you click on button 1 element 1 has to show if you click on button 2 element 2 has to show. and so on
now i don't want to put the same code 30 times (example 1) with only different numbers. I think it can be shorter (example 2)
Does anyone know how I can best do this?
example 1:
$("#O1").click(function() {
KSlevel = 1;
alert(KSlevel);
$('#ks' + KSlevel).fadeIn(200);
});
$("#O2").click(function() {
KSlevel = 2;
alert(KSlevel);
$('#ks' + KSlevel).fadeIn(200);
});
example2:
$("#OX").click(function() {
KSlevel = X;
alert(KSlevel);
$('#ks' + KSlevel).fadeIn(200);
});
答案1
得分: 1
以下是翻译好的部分:
HTML:
<button class="test" id="1">点击</button>
<p id="p1" style="display: none;">1</p>
<button class="test" id="2">点击</button>
<p id="p2" style="display: none;">2</p>
<button class="test" id="3">点击</button>
<p id="p3" style="display: none;">3</p>
<button class="test" id="4">点击</button>
<p id="p4" style="display: none;">4</p>
JQuery:
$('.test').click((e) => {
$(`#p${e.target.id}`).fadeIn();
});
你也可以在HTML的onClick属性上运行一个函数,并将一个id放在函数的参数中。函数的其余部分将保持不变。
英文:
There you go:
HTML:
<button class="test" id="1">click</button>
<p id="p1" style="display: none;">1</p>
<button class="test" id="2">click</button>
<p id="p2" style="display: none;">2</p>
<button class="test" id="3">click</button>
<p id="p3" style="display: none;">3</p>
<button class="test" id="4">click</button>
<p id="p4" style="display: none;">4</p>
JQuery:
$('.test').click((e)=>{
$(`#p${e.target.id}`).fadeIn();
});
You can also run a function on HTML's onClick attribute and put an id in the function's parameter. Rest of the function would be the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论