Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  17] [ 4]  / answers: 1 / hits: 32596  / 11 Years ago, fri, march 1, 2013, 12:00:00

I have a bunch of <a> tags on a page that look something like



 <a href=# id=001 onclick=fnaaa(); >...</a>
...
<a href=# id=002 onclick=fnaba(); >...</a>
...
<a href=# id=003 onclick=fncda(); >...</a>


//sometimes maybe like this
<a href=# id=004 onclick=fnagg(); return false; >...</a>
...


Now I have the id passed to the page as a query string , so I originally wanted to do something like



$('a[id=' + id + ']').click();
$('a[id=' + id + ']').trigger(click);


it turns out both of those are not allowed , so if I have the id , how can I call the function that is written in the onclick attribute? I know I can probably get it like this



var funcToCall = $('a[id=' + id + ']').attr('onclick');


but how do I call this funcToCall? remembering that funcToCall may be more then just a function name ex. fnagg(); return false;


More From » jquery

 Answers
18

First of all, the ID attribute has some restrictions, one being that it must start with a letter. After you fix that, I would recommend not using an inline onclick handler.



$(#ID_HERE).click(function(e) {
fnaaa();
e.preventDefault();
});


Then you can trigger it easily:



$(#ID_HERE).triggerHandler(click);


However, if you absolutely must use the ugly onclick, you can invoke it like this:



<a id=foo href=# onclick=alert('test');>Test</a>
var el = document.getElementById('foo');
el.onclick();

[#79893] Thursday, February 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
markusdamienn

Total Points: 167
Total Questions: 119
Total Answers: 93

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;