开发者

How to use javascript to capture click events from multiple forms

There will be 0-10 forms on a page. Each will allow a user to vote on the content of that form. How do I utilize javascript to capture click events for those different forms, and return content to the scope of a specific form. If I dynamically generate id's for the forms, how开发者_JAVA百科 to I account for that in javascript?


If you use the jQuery JavaScript library then you can attach the same function to all forms in one go, and have a reference back to a form inside of a callback function. For example if you were waiting for a form to be submitted by the user to send of an AJAX request you could do this:

// `$('form')` selects all the forms on the page
// `.submit();` will call a function when the submit event is fired on all forms
$('form').submit(function() {
    // Store a reference to this form
    var $thisForm = $(this);

    $.ajax({
        ...
        success: function() {
            // do something with the $thisForm variable which is still in scope.
        }
    });
});


I am uncertain about what you exactly want.

how about assigning onclick event when you are generating the ids.

x.id = idname ; 
x.onclick = func(idname)

and then func decides what to do based on id.


From the question, it looks like you want event delegation. If you're talking about just the click events, they bubble up, so you can use a single handler from the body which delegates to the handler. However, change events do not bubble in IE so you couldn't do that (without trying to trap them in the capture phase in IE)

I'll use jquery so I don't have to worry about cross browser issues, otherwise, the response would be 10 times longer. If you can't use jquery, you'll have to figure out the cross browser madness and implement it yourself. Most frameworks have utilities to do the exact same thing

<form id='dynamic-123' class='songs'> ---- </form>
<form id='dynamic-681' class='events'> ---- </form>

$(document.body).delegate("form", "click", function(e) {
  // This handler will be called when a click is detected within any form.
  // You'll have to use e.target to figure out which form it was. I would
  // add class attributes to the forms that let you respond differently based on 
  // form was clicked.
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜