views:

50

answers:

4

Hi,

I have HTML code similar to

<div class="menu">
    <div>Latest</div>
    <div>Oldest</div>
</div>

I loop through all items in JavaScript and bind a click event listener on them. Now in the event callback, I'd like to know what data to fetch via AJAX. How do I figure that out from one item? I know that I should put something in the item to determine the type of item, but where do I put it?

A: 

I am not 100% sure on what you are asking. But if you are looking to put "user data" on the elements you could just use a attribute and select the attribute in JavaScript.

<div class="menu">
    <div userdata="Latest">Latest</div>
    <div userdata="Oldest">Oldest</div>
</div>
Brian
When doing so, please use the HTML 5-compliant `data-…` attributes.
Marcel Korpel
+5  A: 

If you're using just divs, using a className would be convenient and valid. Like this:

<div class="menu">
    <div class="latest">Latest</div>
    <div class="oldest">Oldest</div>
</div>

...

function divClickHandler(event) {
  var div = event.target;
  if (div.className == 'latest')
    // load latest
  else if (div.className == 'oldest')
    // load oldest
}

If you're using html5, an even better solution would be using custom data- attributes; like this:

<div class="menu">
    <div data-type="latest">Latest</div>
    <div data-type="oldest">Oldest</div>
</div>

The most elegant solution would be using a tags instead of the divs and intercept their clicks:

<div class="menu">
    <a href="?whatever">Latest</a>
    <a href="?barfoo">Oldest</a>
</div>

...

function aClickHandler(event) {
  var a = event.target;
  // do your ajax call using a.href
  return false;
}
kkyy
+1  A: 

You could specify this via a class or id. e.G.

<div class="menu">
    <div class="latest">Latest</div>
    <div class="oldest">Oldest</div>
</div>

Test it with element.className in the loop.

joni
A: 

It would have been beneficial to specify what kind of elements you are referring to.

However, you can recognize an element from its id. Or you can specify your own attribute and retrieve it.

Example:

click here

// javascript $("#mybtn).bind('click', function() {

var attr = $(this).attr('attr1');

// use attr value for any specific logic

});

deepsat