相同功能,不同数字

huangapple go评论59阅读模式
英文:

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:

&lt;button class=&quot;test&quot; id=&quot;1&quot;&gt;click&lt;/button&gt;
&lt;p id=&quot;p1&quot; style=&quot;display: none;&quot;&gt;1&lt;/p&gt;

&lt;button class=&quot;test&quot; id=&quot;2&quot;&gt;click&lt;/button&gt;
&lt;p id=&quot;p2&quot; style=&quot;display: none;&quot;&gt;2&lt;/p&gt;

&lt;button class=&quot;test&quot; id=&quot;3&quot;&gt;click&lt;/button&gt;
&lt;p id=&quot;p3&quot; style=&quot;display: none;&quot;&gt;3&lt;/p&gt;

&lt;button class=&quot;test&quot; id=&quot;4&quot;&gt;click&lt;/button&gt;
&lt;p id=&quot;p4&quot; style=&quot;display: none;&quot;&gt;4&lt;/p&gt;

JQuery:

$(&#39;.test&#39;).click((e)=&gt;{
     $(`#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.

huangapple
  • 本文由 发表于 2020年1月3日 18:34:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定