简体   繁体   中英

Opening all links with class popup in a new window

I have lots of links on my page with class="popup" .

I want all of these to open in a new window.

Any nice way to define this with Javascript?

I am using .live() to support links that might be added later to the DOM. If you are not adding links from event handlers, Ajax callbacks, etc., you can simply use .click() .

$('a.popup').live('click', function (e) {
     window.open(this.href);
     e.preventDefault();
});

Please note, that according to the current HTML5 spec, you can also use:

<a href="#" target="_blank"></a>

as you previously could in HTML4. This way, you do not need Javascript. Using target is not recommended though on an XHTML doctype, because it is not considered a valid attribute.

UPDATE: From the jQuery documentation

As of jQuery 1.7, the.live() method is deprecated. Use.on() to attach event handlers. Users of older versions of jQuery should use.delegate() in preference to.live().

If you need help changing your code, be sure to check previous StackOverflow questions. Using the SO search [jquery] live deprecated is a good start.

You can put this in your $(document).ready()

$('a.popup').attr('TARGET', '_BLANK');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM