jQuery Checkbox/Target _Blank
I have the following jQuery on my website:
$(function() {
$('#newtab').toggle(function() {
$('a').attr('target', '_blank');
},
function() {
$('a').removeAttr('target');
});
});
The code is for a checkbox that toggles the target of links on my page (when checked, links 开发者_高级运维open in a new tab (target="_blank"
), otherwise, they open in the same page.
I have two issues:
- I want to make it so only links in a particular
div
are affected by the toggle (I essentially just don't want links in my menu to be affected by it). - When clicking the checkbox, the check is never shown for some reason. I have
<input type="checkbox" id="newtab" /><label for="newtab">Open links in new tab</label>
on my page which shows the checkbox (unselected). When I click on it, it changes the target attribute, but the checkbox never appears to be selected; it still shows the empty box. Clicking the checkbox again removes the target attribute as expected.
Thanks.
This should solve your problem: http://jsfiddle.net/UJMgQ/2/
$(function () {
$('#newtab').click(function () {
if ($(this).is(':checked')) {
$('#wanted a').attr('target', '_blank');
} else {
$('#wanted a').removeAttr('target');
}
});
});
To limit the a
's that are selected just change #wanted
to what ever div
(container) the a
's you want are in. It works like a css selector.
For part 1: $('.divYouWant a').attr(...)
will limit it, just like a CSS selector would.
For part 2: According to the docs of toggle() "The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.". If you don't want that, either use .click(), or just set $('#newtab').checked
equal to one in the selected function, and 0 for the unselected function.
- Try:
$('#mydiv').find('a').attr('target', '_blank');
- I think toggle wants you to return
true
to make the click event propagate to the checkbox. Not sure, but checking the docs may be in order here...
Nevermind, docs say that toggle prevents propagation. Perhaps use something like $.change() instead, and use the value of the checked property to set the values you want.
精彩评论