javascript to find the caller div. (or any other dom object)
I have the following html page:
<div id="a" onclick ="javascript:click();">a</div>
<div id="b" onclick ="javascript:click();">b</div>
<div id="c" onclick ="javascript:click();">c</div>
Now, The javascript function:
function click() {
// how do I know if it was 'a' , 'b' or 'c' to call me
}
Does anybod开发者_C百科y know how to find (in every browser) which div was the caller in the 'called' click function ?
Many Thanks Erik
Something along the lines of:
js:
function click(elem){
alert(elem.id);
}
html:
<div id="a" onclick ="javascript:click(this);">a</div>
<div id="b" onclick ="javascript:click(this);">b</div>
<div id="c" onclick ="javascript:click(this);">c</div>
Hint:
<script>
function click(me) {
alert(me.id);
}
</script>
...
<div id="c" onclick ="click(this);">c</div>
Pass this
as function argument:
<div id="a" onclick ="javascript:click(this);">a</div>
<div id="b" onclick ="javascript:click(this);">b</div>
<div id="c" onclick ="javascript:click(this);">c</div>
And here is the function:
function click(el) {
alert(el.id);
}
It would have been easier and unobtrusive with jQuery though:
$('div').click(function(){
alert(this.id);
});
精彩评论