开发者

Setting an attribute in jQuery and then retrieving it

I have

var results="<div title='"+id+"'><img src='"+thumb+"'></div>";

I'm rendering this out to the page, and then later trying to retrieve the id variable. To do this, I have:

$("#results").click(function() { var id=$(this).attr("title"); });

Right now, id is returning as undefined. I think I'm not se开发者_如何转开发tting the attribute right in the first place. How do I do this correctly? Let me know if I need to provide more detail.


In the click handler this is pointing to #results and the title is being set to some other div. You need to find that div and get the title attribute from it. If #results is the same div to which you are setting the title then there should be id="results" in that div since you are selecting it by id.

results is a JavaScript varaible, are you looking for something like this

$(results).click(function() { var id=$(this).attr("title"); });


To get the ID, you need to retrieve "id" instead of "title":

var id=$(this).attr("id");

...though you really don't need a jQuery method for this:

var id = this.id;

Or if you're trying to select the element by its variable name "results", you just can't do that. It needs to be an attribute of the element itself, not the name of some variable reference to it.


From your example there, what has the id="results" on it? I'm assuming it's not your div with the title attribute.

try this:

$("#results div[title]").click(function() { var id=$(this).attr("title"); });

or better yet just add a class to that div

var results="<div class='result' title='"+id+"'><img src='"+thumb+"'></div>";

$("#results .result").click(function() { var id=$(this).attr("title"); });


This code doesn't make a lot of sense unless you left something out. I'm assuming you're adding results to the DOM somehow? If that's the case, you haven't assigned it an ID unless there is more javascript code missing. So when you retreive the identifier with ID of "results" are you getting anything?

Try printing out the length of $("#results") ...are you getting anything?

attr("title") is the correct way to read an attribute, but this is not synonymous with ID, so I'm a bit confused. Your ID is of course results, as indicated by your selector.


Try changing your code so you can reference the div - I'm using the id "theDiv", but you can use anything:

var results="<div id='theDiv' title='"+id+"'><img src='"+thumb+"'></div>";

I'm rendering this out to the page, and then later trying to retrieve the id variable. To do this, I have:

$("#results").click(function() { var id=$('#theDiv').attr("title"); });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜