Reputation: 12048
This might be a duplicate question, however I did search and I got so many different answers that I don't know which to use or how to do this.
<?
if(isset($content))
{
$i = 1;
foreach($content as $item)
{
echo "<li><a href='#' name='" . $item['id'] . "'>" . $item['title'] . "</a></li>";
$i++;
}
}
?>
I've added a function to these links with jQuery to handle an ajax call. I select the links as follows:
$("#tips_list ul li a").click(function(e) { //... }
However, this doesn't make a lot of sense because now you have to click on the actual text instead of the list item. So I figured I'd re-structure my HTML so the anchor tag wraps around the li
tag.
`<a href="#" name=""><li>foo</li></a>`
I then changed my jQuery code accordingly:
$("#tips_list ul a li").click(function(e) { //... }
However, now, when I click.. it grabs the list item tag as $(this)
; which means I can't really grab the name attribute from the anchor tag. So! What I need to do is to grab the name
attribute from the parent anchor tag. And I honestly have no clue what the easiest way to do this is. I'm not that experienced with jQuery.
Thanks a lot for helping me!
Upvotes: 1
Views: 441
Reputation: 174
How about going back to the original method, and set #tips_list ul li a {display:block}
in your CSS? That should make the a expand and take up the whole li, making the whole li seem clickable. Your original code should then work fine.
Upvotes: 1
Reputation: 10814
To get the parent of an element you just need to use
$(this).parent()
So I would do this:
$(this).parent('a').attr('name');
Upvotes: 1
Reputation: 79069
Keep the old markup. The later one is quite cranky and use the following script.
$("#tips_list ul li").click(function(e) {
var name = $(this).children("a").attr("name");
alert(name);
}
Upvotes: 3