views:

14

answers:

1

I'm sure a lot of you have come across this dilemma at one time or another:

I have a block-level HTML element that contains multiple block-level and inline-level elements, e.g.

<div id="ajax">
   <h2>Something</h2>
   <div class="icon"></div>
   <div class="clear"></div>
   <div class="somethingelse"><h3>blah</h3></div>
</div>

I simply want to attach a jQuery ajax() event to a click on #ajax (the top-level element), but I need to pass through a few parameters to the server-side script.

One possible way I'm seeing is simply replacing div#ajax with a#ajax, which would allow me to add something like href="param=value&this=that", but this would render the page invalid: there can't be any block-level elements (<div>) inside of an inline element (<a>).

Another possible way would be adding a rel attribute to div#ajax, which would also mean neglecting XHTML validation.

I don't want to go adding inline onclick events to divs, that's a little too far out... Also, turning all children of div#ajax into e.g. <span> would be a major pita.

How would you handle this?

Thanks!

+1  A: 

There are several ways to go about this while maintaining XHTML validity, or at least remaining full functional in all browsers:

First option, put the parameters directly in JavaScript somewhere, this is the simplest.


Second, if you can't do this in the script, you can use the anchor, but inside, not wrapping it, like this:

<div id="ajax">
   <h2>Something</h2>
   <div class="icon"></div>
   <div class="clear"></div>
   <div class="somethingelse"><h3>blah</h3></div>
   <a class="params" href="page.htm?param=value&this=that"></a>
</div>

CSS Hiding it:

.params { display: none; }

And jQuery using it:

$("#ajax").click(function() {
   $.ajax({
     url: $(this).find(".params").attr("href");
     success: function() {
       //do something
     }
   });
});

Third, use HTML5 data attributes, this will break strict XHTML validity, but a great future way to go, it'll cause no problems in current browsers.


Last option (that I can think of), use the jQuery metadata plugin or storing what you want.

Nick Craver
Thanks Nick, I like the added link inside and I really love the HTML5 approach. That one will also break transitional XHTML validity, but right now I think I'm taking that too seriously anyway... I'll probably end up doing that after all. Thanks!
bobsoap