Onclick not triggered on objects
So I have a table with X rows in it. I have the following HTML code:
<tr id='row1' onClick="FormTRClick('1')"><td><a href='#'>Bla</a></td></tr>
<tr id='row2' onClick="FormTRClick('2')"><td><a href='#'>Bla</a></td></tr>
<tr id='row3开发者_如何学Python' onClick="FormTRClick('3')"><td><a href='#'>Bla</a></td></tr>
<tr id='row4' onClick="FormTRClick('4')"><td><a href='#'>Bla</a></td></tr>
Now, when you click on the hyperlink 'Bla' you will also activate the OnClick event. Is there a way to only trigger the OnClick event when you don't click on an object (like button, image, href) but only on the table row itself?
My FormTRClick() function looks as follow:
function FormTRClick(ctrl) {
if (document.getElementById('chk' + ctrl).checked == true) {
document.getElementById('chk' + ctrl).checked = false;
} else {
document.getElementById('chk' + ctrl).checked = true;
}
}
I know I could also use the inverse document.getElementById('chk' + ctrl).checked = !document.getElementById('chk' + ctrl).checked
but that's not the point, I have extra code in there.
Thanks
You'll want to attach an event listener to those clicks, and stop the propogation:
https://developer.mozilla.org/en/DOM/event.stopPropagation
Alternatively, you can check for the target element:
HTML:
<tr id='row1' onClick="FormTRClick(event, '1')"><td><a href='#'>Bla</a></td></tr>
<tr id='row2' onClick="FormTRClick(event, '2')"><td><a href='#'>Bla</a></td></tr>
<tr id='row3' onClick="FormTRClick(event, '3')"><td><a href='#'>Bla</a></td></tr>
<tr id='row4' onClick="FormTRClick(event, '4')"><td><a href='#'>Bla</a></td></tr>
Javascript:
function FormTRClick(event, ctrl) {
if (event.target.tagName != 'A' && document.getElementById('chk' + ctrl).checked == true) {
document.getElementById('chk' + ctrl).checked = false;
} else {
document.getElementById('chk' + ctrl).checked = true;
}
}
Since the links are part of the table row, they will always trigger the onclick for the table row when you click them.
There is a simple workaround, however...
<tr id='row1' onClick="FormTRClick('1');"><td><a href='#' onmouseover="linkOver();" onmouseout="linkOut();">Bla</a></td></tr>
...and some javascript...
var linkIsOver = false;
function FormTRClick(ctrl) {
if (!linkIsOver) {
if (document.getElementById('chk' + ctrl).checked == true) {
document.getElementById('chk' + ctrl).checked = false;
} else {
document.getElementById('chk' + ctrl).checked = true;
}
}
}
function linkOver () {
linkIsOver = true;
}
function linkOut () {
linkIsOver = false;
}
So do it like that. In HTML:
<tr id='row1' onClick="FormTRClick(this, '1')"><td><a href='#'>Bla</a></td></tr>
In JS:
function FormTRClick(elem, ctrl) {
if (elem.tagName != 'TR') return;
//do what you need
}
UPDATED WITH UPPER-CASE TAG NAME
精彩评论