views:

320

answers:

3

I am trying to get the html value of a linked clicked. The links are created dynamically with Ajax so I don't think .bind will work and I don't have latest version with .live

$('div#message').click(function() {
  var valueSelected = $(this).html();  // picks up the whole id. I juust want single href!          
  alert(valueSelected);
  return false;
});



<div id="message">
<br/>
<a class="doYouMean" href="#">location A</a>
<br/>
<a class="doYouMean" href="#">location B</a>
<br/>
<a class="doYouMean" href="#">location C</a>
<br/>
<a class="doYouMean" href="#">location D</a>
<br/>
<a class="doYouMean" href="#">location E</a>
<br/>
</div>
+1  A: 

Apply your handler to just the links, in the callback of the AJAX load.

$('div#message').load( myUrl, function() {
    $('div#message a').click(function() {
       var valueSelected = $(this).html();
       alert(valueSelected);
       return false;
    });
});
tvanfosson
A: 

You have 2 options -

  1. Use the LiveQuery plugin which is what we used before .live came along
  2. Rebind your function to the click event after each successful ajax call. (Recommended)
James Westgate
#2 did the trick!
davidP
A: 

You should really be using the latest version if you can help it.

If it's the ".doYouMean" elements that are added using AJAX, and #message is always there, try:

$('#message').bind('click', function (event) {
  var target = event.currentTarget;
  if ($('.doYouMean').filter(target)) {
    // target is the .doYouMean that was clicked: Handle here
  };
});

(This works: http://www.jsfiddle.net/SuVzv/)

Matt