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?

2
  • btw, that's a good read on the subject: stackoverflow.com/questions/12627443/jquery-click-vs-onclick Commented Nov 4, 2013 at 20:15
  • @Leon Thanks for the post. I ran across that post multiple times while a was searching for an answer! Commented Nov 4, 2013 at 20:20

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Ehh... nothing out of the ordinary, data-* is just a custom attribute that will pass HTML validation, perfect for something like this.
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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.