jQuery多个单击事件处理程序,具有不同的函数参数,重构。

时间:2016-06-30 20:06:55

标签: jquery function event-handling refactoring

我有以下HTML代码,带有以下jQuery代码,引用名为Game的构造函数和一个名为roll的函数。我根据你在HTML文件中按哪个按钮向每个偶数处理程序传递一个不同的参数,但是我想知道你将如何重构这个?非常感谢

HTML代码:

while(true){doStuff()}

jQuery代码:

<section>
      <h1>Score:</h1>
      <h1 id="score"></h1>
      <p>
        <button id="1">1</button>
        <button id="2">2</button>
        <button id="3">3</button>
        <button id="4">4</button>
        <button id="5">5</button>
        <button id="6">6</button>
        <button id="7">7</button>
        <button id="8">8</button>
        <button id="9">9</button>
        <button id="10">10</button>
      </p>
    </section>

4 个答案:

答案 0 :(得分:1)

我建议采用两种不同的方法:

1)使用服务器端语言,例如PHP甚至框架来生成布局dinamicaly

2)使用相同的结构,尝试应用以下代码:

 <section>
  <h1>Score:</h1>
  <h1 id="score"></h1>
  <p>
    <button class="gameBtn" id="1">1</button>
    <button class="gameBtn" id="2">2</button>
    <button class="gameBtn" id="3">3</button>
    <button class="gameBtn" id="4">4</button>
    <button class="gameBtn" id="5">5</button>
        <button class="gameBtn" id="6">6</button>
        <button class="gameBtn" id="7">7</button>
        <button class="gameBtn" id="8">8</button>
        <button class="gameBtn" id="9">9</button>
        <button class="gameBtn" id="10">10</button>
      </p>
    </section>

和jquery:

$(document).ready(function() {
var game = new Game();
$('#score').text(game.score());
$('.gameBtn').on('click', function() {
game.roll(parseInt($(this).attr('id')));
$('#score').text(game.score());
});

});

答案 1 :(得分:1)

尝试以下操作,您可以摆脱所有冗余事件处理程序。

HTML

<section>
      <h1>Score:</h1>
      <h1 id="score"></h1>
      <p>
        <button data-id="1" id="1">1</button>
        <button data-id="2" id="2">2</button>
        <button data-id="3" id="3">3</button>
        <button data-id="4" id="4">4</button>
        ..........
      </p>
</section>

JQUERY

$('button').click(function(){
    var id = $(this).data('id')
    game.roll(id);
    $('#score').text(game.score());
});

答案 2 :(得分:0)

您可以执行以下操作:

&#13;
&#13;
$(document).ready(function() {
  var game = new Game();
  $('#score').text(game.score());
  $('.some_class').on('click', function(){
        game.roll($(this).attr('id'));
        $('#score').text(game.score());
  });
});
&#13;
&#13;
&#13;

答案 3 :(得分:0)

你可以把名为&#34; call-roll&#34; (例如)在每个按钮中,并将你的js代码改为:

&#13;
&#13;
$(document).ready(function(){
    $('.call-roll').click(function(){
    	var value = $(this).text();
    	game.roll(value);
    	$('#score').text(game.score());
    });
});
&#13;
&#13;
&#13;