如何在jQuery的attr()代码中添加target="_blank"?JS代码怎么实现新窗口打开?
Hey there! Let's break down your two questions one by one—both are focused on getting content to open in a new browser tab/window, so we'll cover the jQuery and vanilla JS scenarios clearly.
target="_blank" with jQuery's attr() Method Using jQuery's attr() method to add the target="_blank" attribute is straightforward, and there are a couple of ways to do it depending on your use case:
- Target a single element (e.g., an anchor tag with ID
main-link):$('#main-link').attr('target', '_blank'); - Target multiple elements (e.g., all anchor tags on the page):
$('a').attr('target', '_blank'); - Bonus: Add security attributes alongside it
For external links, it's a good practice to addrel="noopener noreferrer"to prevent potential security risks (this stops the new tab from accessing the original page'swindowobject). You can set multiple attributes at once by passing an object toattr():$('#external-link').attr({ 'target': '_blank', 'rel': 'noopener noreferrer' });
Since you didn't share your exact code, I'll cover the most common scenarios where this issue pops up, along with fixes:
Scenario 1: You're using window.location.href
If your code is using window.location.href = 'your-url' to navigate, this will always open in the same tab. To switch to a new window/tab, replace it with window.open():
// Replace this: window.location.href = 'https://your-content-url.com'; // With this: window.open('https://your-content-url.com', '_blank');
Important note: Browsers will often block window.open() if it's not triggered by a user interaction (like a click or button press). Make sure this code runs inside a callback for a user-initiated event (e.g., click handler).
Scenario 2: You're dynamically creating elements
If you're building links or buttons dynamically, you need to explicitly set the target attribute (and security rel attribute) before triggering the navigation:
- Vanilla JavaScript example:
const dynamicLink = document.createElement('a'); dynamicLink.href = 'https://your-content-url.com'; dynamicLink.target = '_blank'; dynamicLink.rel = 'noopener noreferrer'; // Trigger the click to open the new tab dynamicLink.click(); - jQuery dynamic element example:
$('<a>', { href: 'https://your-content-url.com', target: '_blank', rel: 'noopener noreferrer' }).appendTo('body').click();
Scenario 3: You're modifying existing elements
If you're updating an existing element's URL but it still opens in the same tab, make sure you've added the target="_blank" attribute to it (just like the first question's solution).
内容的提问来源于stack exchange,提问作者Sonia

