开发者

How to watch input buttons with specified name?

For example I have long list of buttons: <input type=button name=clickbutton onclick='dosomething(this)'>

But instead of putting call to the same function in every button it would be more rat开发者_运维百科ional to add a single listening event that would wait for click of that button with this name. But again, there are many this buttons so I need pass clicked object to a function. For example this function must update a textarea field that is adjacent (nextSibling) to this button.


You could use jQuery:

$('input[name|="clickbutton"]').click(function() {

    var currentButton = $(this);
    alert(currentButton.attr('id'));

});

This attaches a click function to all input elements with a name of 'clickbutton'. currentButton is the input element that was just clicked. The function then alerts the id of the currentButton.

UPDATE: I've created a working example for you here: http://jsfiddle.net/Damien_at_SF/cdsWk/1/

Hope that helps :)


Look up event delegation. This may be what you need. There are many good resources for it on google.

Update: Sorry, I could have put a little more effort into the answer, Here are some results Google Search...

You would then use a switch to determine what action you want to take based on the event.name attribute. Cool thing about that approach is if you have a great deal of elements on the page with events, it sounds like you do, it should make your page feel more responsive; as the browser does not have to deal with the extra overhead of on event per element.


var buttons = document.getElementsByName('clickbutton');
for (var i = 0; i < buttons.length; i++)
    buttons[i].onclick = function(){
        this.nextSibling.innerHTML = 'clicked!';
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜