3

I have always went with the inline onclick approach as such:

<a href="#" id="do-something" onclick="doSomething(<?= $row['id'] ?>); return false;">

But I notice this isn't what the majority of websites do. They tend to do this:

<a href="#" id="do-something">

$("#do-something").click(function(e) {
    e.preventDefault();
    doSomething();
    // --------^
})

The only problem is, how do I get the parameter that I supplied in example one so I can use it in example two? What's the correct process? Maybe add some hidden divs?

SeanWM
  • 15,457
  • 7
  • 48
  • 82
  • btw, that's a good read on the subject: http://stackoverflow.com/questions/12627443/jquery-click-vs-onclick – Leon Nov 04 '13 at 20:15
  • @Leon Thanks for the post. I ran across that post multiple times while a was searching for an answer! – SeanWM Nov 04 '13 at 20:20

2 Answers2

5

Assign that value to a custom data attribute, something like data-row="<? php ... ?>". Now access it with: $(this).data("row");

tymeJV
  • 99,730
  • 13
  • 150
  • 152
  • Ah yes, I've seen that. I wasn't sure if that was the _"correct"_ way to do it. Is there anything I should be aware about before doing this? – SeanWM Nov 04 '13 at 20:14
  • 1
    Ehh... nothing out of the ordinary, `data-*` is just a custom attribute that will pass HTML validation, perfect for something like this. – tymeJV Nov 04 '13 at 20:15
0

One way might be to use data attributes, like this:

<a href="#" id="do-something" data-row="<?= $row['id'] ?>">

And then this function:

$("#do-something").click(function(e) {
    var row = $(this).data('row');
    e.preventDefault();
    doSomething(row);
});
Matt Sach
  • 1,103
  • 15
  • 36