views:

67

answers:

3

I'm not sure how to best word this, so I'll give it a shot and hopefully revise it as it comes to me.

Using javascript/jQuery, let's say I want to get some data from a clicked element to a function for processing. A couple of options:

OPTION 1:

$('.classOfInterest').click(function() {
      // How can I get 'a' and 'b'?
    var c = $(this).hasClass('cExists'); 
}); 
<a class="cExists classOfInterest" />

OPTION 2:

function processClick(string a, string b) {
    // How can I get a reference to the calling element, similar to $(this) in the event handler?
    var c;  // here I want to determine whether the calling element has class 'cExists'    
}
<a class="cExists" href="javascript:processClick('a', 'b')" />
+2  A: 

Option 1 is the more jQuery-ish way to accomplish what you're trying to do. You can get a and b by making them attributes of the link:

 $('.classOfInterest').click(function() {
       // How can I get 'a' and 'b'?
     var c = $(this).hasClass('cExists'); 
     alert(this.attr('a') + ' ' + this. attr('b'));
 }); 
 <a class="cExists classOfInterest" a="hi" b="mom" />
Tom Ritter
Does this validate?
Paolo Bergantino
As XHTML? Probably not. But getting your page to validate as XHTML is a giant religious debate.
Tom Ritter
Oh, I don't really care, just curiosity more than anything. I'm more about Getting It Done (tm).
Paolo Bergantino
Thanks, this accomplishes what I want to do. I just wasn't sure if creating your own attributes is considered a good practice...?
Justin
Custom attributes in rendered (from the server) html is not very good.
cherouvim
+1  A: 

JS:

function processClick(id, a, b) {
  $(id).click(function() {
    var c = $(this).hasClass('cExists'); 
    alert(a + ' ' + b);
  }); 
}

HTML:

<script type="text/javascript">processClick("foo123", "a", "b")</script>
<a class="cExists" id="foo123" href="#">

Another option if you want to avoid the inline js inside the html is to do something like the following.
JS:

$(function() {
  $('cExists').click(function() {
    var c = $(this).hasClass('cExists');
    var a = $(this).attr('title').split(":")[0];
    var b = $(this).attr('title').split(":")[1];
    alert(a + ' ' + b);
  }); 
});

HTML:

<a class="cExists" href="#" title="foo:bar">

But this way you'll be exposing the a and b variables on the element's title.

cherouvim
A: 

If you're looking for a standards-compliant solution, you might consider using a data URI, e.g.

<a href="data:text/csv,a-data,b-data">foo</a>

To get the data, read out the href attribute and use split() to extract the comma-separated values. Remember to prevent the default action via preventDefault() or return false when handling the click event - otherwise, browsers will try to download the data or just fail.

Christoph