apply a click to parent of a tag (jquery)
I have alot of:
<li><a href="google.com">LINKY</a></li>
type links on my site and much prefere the whole Li to be clickable instead of just the text. So was thinking of applying some nice jquery that will hunt any $('li a') down an开发者_StackOverflowd make it so when you click the <li>
it will trigger the click on a <a>
$('li a').each(function(index) {
$(this).parent().bind('click', function() {
$(this).children().click();
});
});
This fails to work but im not sure why? any ideas?
Wouldn't it be better to stretch the anchor to the size of LI?
li > a {
display: block;
width: 100%;
/* optionally height: some height */
}
It is much simpler if you just bind the click event to the <li>
element.
Event bubbling will ensure that it is triggered when you click the <a>
as well.
Here's an example: http://jsfiddle.net/MB9Fm/
$('li:has( > a)').click(function() {
alert('I was clicked');
return false;
});
EDIT:
I may have misunderstood the intention for the click
handler. If all you wanted to do was visit the href location, I'd agree with the CSS solutions of possible. Otherwise, using js, do something like this:
http://jsfiddle.net/nkGga/
$('li:has( > a)').click(function() {
window.location = $(this).children('a').attr('href');
});
The way you were calling .click()
in your comment would cause an infinite loop, an I'm not sure that it would actually take you to the href location anyway.
Calling click() on a link doesn't perform the default action (going to the address). You could manually make a click handler:
$('li a').each(function(index) {
$(this).parent().bind('click', function() {
window.location = $(this).children().attr('href');
});
});
Look into the .delegate()
functionality added in 1.4.2, this is more suited to your desires.
$("li").delegate("a", "click", function(event){
//do what you want here
return false; //prevent default action and prevent bubbling up
});
Try this:
$('li:has(a)').each(function() {
$(this).bind('click', function(index){
$(this).find('a').trigger('click');
});
});
精彩评论