referencing (this) in a function
I have elements being generated by dynamic html, I would like to reference the particular href that is calling the function when one of many may be calling it.
<a href="javascript:Foo(this)">Link</a>
Does开发者_Go百科 not work when I try to reference $(this). Is there another way to do this or do I have to make dynamic ids?
<a href="javascript:Foo(this.href)">Link</a>
will work if you want to pass the href.
However, onsomething handlers in the html code are not jqueryish at all. Give your links a class and setup a live handler:
$('.mylink').live('click', function() {
// do whatever you want with this or $(this) or this.href or $(this).attr('href')
});
putting the js parts in the href
attribute is a bad idea. best practice is adding a handler with addEventListener
but here you can get away with setting onclick
directly.
<a href="#" onclick="Foo(event);">Link</a>
and your function would be like
function Foo(e) {
var a = e.target || e.srcElement;
// TODO: stuff
if (e.preventDefault) {
e.preventDefault();
}
else {
return false;
}
}
so when you click the link, Foo
is called with the event as a paremeter. the event object has a reference to the source element, either as target
in standards browsers or srcElement
in IE. the preventDefault
/return false;
combo at the end prevents the browser from "following" the link to #.
edit: on second thought, since you have many links, using jquery to add handlers the recommended way is probably better (although the first solution is still fine).
...
<a id="A5" href="#" >Link</a>
<a id="A6" href="#" >Link</a>
<a id="A7" href="#" >Link</a>
...
<script>
$('a').click(Foo);
</script>
No point in using the javascript:
pseudo protocol handler.
Use
<a href="#" onclick="Foo(this);">Link</a>
instead.
精彩评论