问题
How to call an onchange event in a table cell (td) for a form tag in it with Chrome? The following code works for me for all browsers except for chrome. Surprising it works with Opera 15 (should use the same engine (webkit/blink) like the newest Google Chrome).
<table><tr>
<td onchange="bla()">
<select>
<option value="n">foo</option>
<option value="n">foo</option>
<option value="n">foo</option>
<option value="n">foo</option>
<option value="n">foo</option>
</select>
</td>
<td onchange="bla()">
<input type="text" />
</td>
<td>
</td>
</tr></table>
<script>
function bla() {
alert('something changed...');
}
</script>
I know it is possible to bind the event to the select tag but for my web-application it won't work that well
回答1:
The reason why the onchange
doesn't work as it should is because it's not the cell that changes, it's the form element inside. Sure, if you click on a tables contents, the table is clicked, too. That makes sense: you can't open a door inside a house without opening the front door first.
You can, however, go inside a room, cut your hair (fire a change-event on yourself) without changing the room where this event took place. In that respect, it makes sense the change event doesn't fire on the parent cell.
The event does traverse the DOM, though, and it does pass the table cell, so you can pick it up there, but not with HTML attributes. (BTW: try to use those as little as possible).
Try binding a listener to the entire table in JS. That way, there's only 1 listener that works for all events (it's called event delegation):
//assume tbl has id foobar:
document.getElementById('foobar').addEventListener('change',function(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
var name = target.id || target.getAttribute('name');
alert('the ' + name + ' element changed!');
},false);
Here's a slightly more complex version of event delegation, which also deals with change events on select elements in IE8. (the change event doesn't bubble in old IE's).
A couple of links:
- As always: MDN
- An article on How delegation works, and how easy it really is
- And good ol' quirksmode: a comprehensive overview on event order/event models
来源:https://stackoverflow.com/questions/17470715/onchange-event-for-html-form-elements-in-td-tag-with-chrome