Problem with popping new window via jquery each method (opening more than one window)
I've created a JS Fiddle at http://jsfiddle.net/Vcftv/2/ that illustrates the problem.
I have some promos/modules which I'm turning into big target links via JS. Basically, the entire promo/module becomes a link, not just a tiny child anchor/html text link. You can click anywhere on the promo/module to follow the child href.
I need some of these to open the href in a new window - I'm just hooking into the target attribute for this. If the link has a target attribute, that means to pop a new window. I'm getting the problem of multiple windows opening when I do some testing and click-throughs.
In the JS fiddle, the first module follows the href in the window. The second and third should pop new windows. They're not quite working right, sometimes one will work fine, but when yo开发者_如何学编程u close the new window and click the link again it'll pop the url in 2 new windows.
Anyone have any ideas?
The problem is that every time a user hovers over the div, your attaching another click event listener! See my edit and notice in the console how often the 'attaching click listener' call is made.
Kelly's solution is far simpler, but the problem with your implementation is as I've described. This edit fixes the problem.
You're making this much more complicated than it needs to be. Instead, do something like this in your JS:
$('.promoBigLink').click(function () {
window.open($(this).find('a').attr('href'));
});
This code takes all of the elements with the promoBigLink
class and opens href
of the first anchor element it finds in its children.
Assuming, of course, that the first anchor element in each promoBigLink
is the one that should be visited. Move the CSS styling into a <style>
tag or a separate file. You may have to handle the case where someone clicks the anchor tag itself.
Hope this helps!
A possibly better solution is to move up the a
so that it fills the area completely. If you give that a
a CSS of text-decoration: none
, it looks the same way and does not have quirks. It's also more accessible since you can now also right-click on the whole area to copy the URL, etc.
You'd need to wrap the div
into a new a
which now delegates the link and target.
http://jsfiddle.net/pimvdb/Vcftv/6/
(function($) {
$.fn.promoBigLink = function() {
return this.wrap(function() {
var href = $(this).find("a").attr('href'), // save href + target
target = $(this).find("a").attr('target');
// wrap div into new a with href + target, with added class
return $("<a>", {href: href,
target: target}).addClass("biglink");
});
};
})(jQuery);
$(function() {
$('div.promoBigLink').promoBigLink();
});
The problem is that every time you hover over the link it is readding the click event.
You can in the out listener of the hover use jquery unbind to unbind the click event.
$(this).unbind('click');
However, it would be best to refactor your code using some of the other suggestions.
精彩评论