开发者

How to select a button id when the button in clicked injavascript/jquery

I am new to javascript/jquery . I have a small question. I have some thing like the following in the java script file.

<button id="button1" onclick=click() />
<button id="button2" onclick=click() />
<button id="button3" onclick=click() />

so the click function looks like the follwoing

click(id){


/do some 开发者_JAVA百科thing
}

so my question is when ever the button is clicked how can we pass the button id to the function.

<button id="button1" onclick=click("how to pass the button id value to this function") />

how can we pass the button id like "button1" to the click function when ever the button is clicked.. I would really appreciate if some one can answer to my question..

Thanks, Swati


I advise the use of unobtrusive script as always, but if you have to have it inline use this, for example:

<button id="button1" onclick="click(this.id)" />

The unobtrusive way would look like this:

$("button").click(function() {
  click(this.id);
});


You don't need to.

function handleClick(){
    //use $(this).attr("id");
    //or $(this) to refer to the object being clicked
}

$(document).ready(function(){
   $('#myButton').click(handleClick);
});


That not very jQuery-ish. You should rather use event listeners:

$(function() {
    $('#button1,#button2,#button3').click(clicked);
    function clicked() {
        // "this" will refer to the clicked button inside the function
        alert($(this).attr('id'));
    }
});


For starters: Don't use onclick(). This is the way to do it properly.

When you get your head around all this and think "boy that's a load of cowpat to write for a litte event!", turn towards jquery.

Doing the same in jquery is simple.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜