Attributes.Add - works independently, not together
I have two attributes I would like to assign to the same event:
ddlBuyer.Attributes.Add("onclick", "$('#tbxProdAC').val('');");
ddlBuyer.Attributes.Add("onclick", "$('#txtbxHowMany').val('');");
If I comment one out, the other other works fine. But if I just leave both lines in, only one is fired.
开发者_如何学GoCan someone explain to me the logic behind this and further to that, how I should nest this so that when ddlBuyer executes the onclick event, both txtbxHowMany & tbxProdAC return the value of ''>
You can only add a single attribute with a given name, so the second one you are adding replaces the first one. It's the equivalent of having two "onclick" attributes in an HTML tag. Won't work.
This doesn't mean you can't fire multiple functions in response to a given event, however. You can, for example, do
ddlBuyer.onclick = function() {
//first thing to do
//second thing to do
};
Another way to do this is to use the jQuery library; jQuery's "bind" command can bind multiple functions to a single event. This has the advantage that you don't have to worry that you're overwriting an event binding added somewhere else (which the above examples will do).
Try:
// Split lines for readability.
ddlBuyer.Attributes.Add("onclick", "function(){
$('#tbxProdAC').val('');
$('txtbxHowMany').val('');
};");
Or:
ddlBuyer.Attributes.Add("onclick",
"$('#tbxProdAC').val('');
$('txtbxHowMany').val('');");
Instead of hard-coding onclick functions into the markup, generate client-side code on the server-side that binds onclick events on the client-side. Probably go with a framework like jQuery to do this.
精彩评论