سؤال

I first tried this code at it works.

$(function(){
    $('#k1').click(function(){
        $('#textbox').empty();
        $('#textbox').prepend('hello');
    });
    $('#k2').click(function(){
        $('#textbox').empty();
        $('#textbox').prepend('hola');
    });
    $('#k3').click(function(){
        $('#textbox').empty();
        $('#textbox').prepend('bonjour');
    });
});

However, I must only have ONE event handler, and I'm pretty sure the code above doesn't count as one. What I need to have is three different buttons: each button showing its own text, for example: button1: hello button2: hola button3: bonjour

Any tips?

هل كانت مفيدة؟

المحلول

You can do it like this:

<input type="text" />
<button>Hola</button>
<button>Hello</button>
<button>Bonjour</button>

$("button").on("click", function(){
    $("input").val($(this).text());
});

fiddle

Within your click handler, $(this) will refer to the element which was clicked to trigger the event, so you can just grab it's text or value or store some arbitrary text on it as a data attribute.

نصائح أخرى

DEMO

First give you buttons a common class (For example, k-button) just so it's cleaner than enumerating all the IDs.

Then you can do something like:

var helloKeyVal = {"k1":"hello","k2":"hola","k3":"bonjour"}

$(".k-button").click(function(){
  $("#textbox").prepend(helloKeyVal[this.id]);
});

You can use custom data-* attribute to store text.

Example

HTML

<input type="text" />
<button data-display-text="Hola">k1</button>
<button data-display-text="Hello">k2</button>
<button data-display-text="Bobjour">k3</button>

JavaScript

$("button").on("click", function(){
    $("input").val($(this).data('display-text'));
});

DEMO

OR

You can use .is()

$('#k1, #k2, #k3').click(function(){
    $('#textbox').empty();
    if($(this)is('#k1,'))
        $('#textbox').prepend('hello');
    if($(this)is('#k2,'))
        $('#textbox').prepend('hola');
    if($(this)is('#k3,'))
        $('#textbox').prepend('bonjour');
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top