Link (this) in function

I have elements generated by dynamic html, I would like to refer to a specific href that calls the function when one of many can call it.

<a href="javascript:Foo(this)">Link</a>

Doesn't work when I try to reference $ (this). Is there any other way to do this or do I need to make dynamic identifiers?

+3
source share
3 answers

<a href="javascript:Foo(this.href)">Link</a> will work if you want to pass href.

However, the onsomething handlers in the html code are not jqueryish at all. Give your links a class and set up a live handler:

$('.mylink').live('click', function() {
    // do whatever you want with this or $(this) or this.href or $(this).attr('href')
});
+5
source

js- href - . addEventListener, onclick .

<a href="#" onclick="Foo(event);">Link</a>

function Foo(e) {

    var a = e.target || e.srcElement;

    // TODO: stuff

    if (e.preventDefault) {
        e.preventDefault();
    }
    else {
        return false;
    }
}

, , Foo . target , srcElement IE. preventDefault/return false; "" #.

edit: , , jquery , , ( ).

...
<a id="A5" href="#" >Link</a>
<a id="A6" href="#" >Link</a>
<a id="A7" href="#" >Link</a>
...

<script>
$('a').click(Foo);
</script>
+1

javascript:.

<a href="#" onclick="Foo(this);">Link</a>

.

-1

Source: https://habr.com/ru/post/1745071/


All Articles