问题
This may be super simple - but I'm struggling to spot what's going on.
On the JS Fiddle: http://jsfiddle.net/3hHAX/
There are two links output to 'Open video modal'.
As the link text suggests these two links should open a model pop-up with the youtube video contained.
This is using the prettyphoto library from: http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
For some reason the click event doesn't trigger on first click. But works on second.
(Haven't included the CSS so doesn't look very modal, but you'll see the content load in below at least for purposes of demo).
Can anyone suggest what's going wrong?
Thanks,
Steve
回答1:
Trigger the click event after you initialize it, and only allow it to be initialized once.
(function($) {
$(".watch-this a, .field-name-field-embed-code a").live('click',function(){
if (!$(this).is(".pPhoto")) {
$(this).prettyPhoto({
social_tools: ''
}).addClass("pPhoto").click();
}
return false;
});
})(jQuery);
Demo: http://jsfiddle.net/3hHAX/3/
Edit for clarification:
This is a very common way of initializing a plugin on dynamic elements. As noted, it is better to initialize on dom ready if your elements are not dynamic.
Note:.live
is depreciated, you should really be using .on
(function($) {
$(document).on("click",".watch-this a, .field-name-field-embed-code a",function(){
if (!$(this).is(".pPhoto")) {
$(this).prettyPhoto({
social_tools: ''
}).addClass("pPhoto").click();
}
return false;
});
})(jQuery);
回答2:
Thanks Guys,
Both responses helped me ultimately solve it.
End solution in the updated JSFiddle:
http://jsfiddle.net/3hHAX/6/
Seems prettyPhoto attaches it's own on click event, and just needed applying to those dom elements.
Thanks, Steve
回答3:
- First of all, never ever use the live method in jquery except in situations where the dom really is out of your control. At the very least you should use the delegate function as the live function will cause a lot of slowdown and a lot of trouble (although it wasn't at fault this time round)
- Secondly, the click event does fire as you can see here, but the prettyPhotos component isn't working the first time round for reasons unknown to me, but as you can see in the previous jsfiddle link it does work with an alert the first time round you click, so it sounds to me as a bug in the prettyphotos script (which Kevin B seems to hackishly solve by triggering a second click event.).
来源:https://stackoverflow.com/questions/9984184/jquery-click-event-requires-two-clicks-to-fire