开发者

Handle Button click Generically

I have 6 buttons on the page. On every button click, I do the following:

$('#btn开发者_StackOverflow1').click(function(){
        $('#txt').val("+");
    }
)

$('#btn2').click(function(){
        $('#txt').val("-");
    }
)

$('#btn3').click(function(){
        $('#txt').val("*");
    }
)

If you observe, the functionality in each click remains the same, the only difference is a new character is added to the textbox. How can i write this generically?


Firstly, I would recommend delegating your event listener, to reduce code clutter. And you can make use of HTML5 data attributes and $.data to get the effect you desire:

<div id="buttons">
  <button id="btn1" data-text="+">Button 1</button>
  <button id="btn2" data-text="-">Button 2</button>
  <button id="btn3" data-text="*">Button 3</button>
</div>

Then in your JS file:

$('#buttons').delegate('button', 'click', function(e) {
  $('#txt').val($(this).data('text'));
});


If your html is formatted like this:

<button type="button" sign="+">Button Value</button>

Then you could handle it like so:

$('#btn1, #btn2, #btn3').click(function(){
    $('#txt').val($(this).attr('sign'));
});

I think this is what pimvdb was suggesting.

Edit: heh. he edited his solution before i hit the submit button


$('#btn1, #btn2, #btn3').click(function(){
        $('#txt').val($(this).data('sign'));
    }
)

and then define in HTML:

<input ... data-sign="+">

and so on.

Demo: http://jsfiddle.net/zvPCz/.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜