2

I have some search results that I'm outputting that are of this form:

  <div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>

There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?

Here's how I'm getting the HTML from above:

$.each(response.data.items, function(i,data)
{
var video_id=data.id; 
var video_title=data.title; 
var video_thumb=data.thumbnail.sqDefault; 

var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));

I tried

 $('div').click(function(){
    alert(this.id);
});

and the alert says "searchresults" (no quotes).

3 Answers 3

2

Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.

$("#searchresults").delegate("div", "click", function() {
    console.log(this.id);
});

See .delegate

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

4 Comments

Is this different from $("#searchresults").find("div").bind("click",fx)?
Functionally, same thing, but you don't have to do it after inserting the new elements, and you don't end up with one event handler for each div.
oops, I meant to ask about live. Does using live instead of bind achieve the same thing as using delegate?
@RSG - yes it does, but live attaches to the document element instead of a chosen 'container', meaning that .delegate has several advantages over the .live approach. I would suggest reading the docs for both methods.
0

You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.

this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:

$('div').click(function(){
    alert(this.id);
});

This code should be something this:

var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);

to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.

Comments

0

you could get the title using $(this).attr("title").val()

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.