jQuery: click() function doesn't work on the <a> element.. why?
I cannot trigger this click on this element
$(this).find('.views-field-field-cover-fid').find('a.imagecache-coverimage').click();
The jQuery path is correct. Indeed if I print it, it gives the co开发者_JAVA百科rrect a element:
console.log($(this).find('.views-field-field-cover-fid').find('a.imagecache-coverimage'));
But for some reason the function click() doesn't work on it. thanks
EDIT:
Now I see that you want to visit the href
of the a
element.
Do this:
window.location = $(this).find('.views-field-field-cover-fid').find('a.imagecache-coverimage').attr('href')
Patrick, the .click()
function behaves differently depending upon how it is used.
If you are hoping to fire a 'click' event handler for the element you selected, then you are using it correctly, but first you will need to give some functionality to that element.
That brings us to the second (and more common) way in which .click()
is used. That is to give functionality to an element. Run this when the DOM loads:
$(document.ready(function() {
$('.views-field-field-cover-fid')
.find('a.imagecache-coverimage')
.click(function() {
alert('I was clicked!');
});
});
Now all elements that match your selector will show the alert when clicked, or when you trigger the event like you did originally.
$(this).find('.views-field-field-cover-fid')
.find('a.imagecache-coverimage')
.click();
http://api.jquery.com/trigger/
Edit: OK, now I understand what you want to do, and sorry that I didn't realize .click() and .trigger('click') are basically equivalent. Another method is to bind the address to the click event.
$(this).find('.views-field-field-cover-fid a.imagecache-coverimage')
.bind("click", function(){
window.location.href = $(this).attr('href');
});
Then you'll be able to trigger the click!
$(this).find('.views-field-field-cover-fid a.imagecache-coverimage')
.trigger('click');
(or .click();
)
Demonstration
What about a single find
?
$(this).find('.views-field-field-cover-fid a.imagecache-coverimage').click(function() {
// stuff
});
精彩评论