简体   繁体   中英

Change a target attribute with jQuery

I'm trying to add target="_new" to every a tag after appending some content to the dom but I'm not being successful.

Please run the snippet and click " Go CORS Go ", wait until the content is fully loaded and try to click on the duck. Despite being an a tag, the new attribute doesn't seem to work. Any insights ?

 var url = encodeURIComponent("https://duckduckgo.com/"); $("button").click(function() { $.getJSON('http://anyorigin.com/get/?url=' + url + '&callback=?', function(data) { var cors = data.contents; $("body").append(cors); $('body a').each(function() { $(this).attr('target', "_blank"); }); }); }); 
 <!DOCTYPE html> <html> <head> <base href="https://duckduckgo.com/" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> </head> <body> <button>Go CORS Go</button> </body> </html> 

Edit the ajax result instead of the result of the page after the append

try the following:

  var newcors = $(cors).find('a').attr('target', "_blank").end();
$('body').append(newcors);

Response returned by ajax had a script which is causing an error, ReferenceError: DDG is not defined(…) which will hald the execution of statements after the ReferenceError

Place your .append statement in try..catch hence error will not affect your later script.

 var url = encodeURIComponent("https://duckduckgo.com/"); $("button").click(function() { $.getJSON('http://anyorigin.com/get/?url=' + url + '&callback=?', function(data) { var cors = data.contents; try { $("body").append(cors); } catch (Exception) { console.log(Exception); } $('body a').attr('target', "_blank"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <button>Go CORS Go</button> 

Update: As suggested in comments, .attr( attributeName, value ) sets one or more attributes for the set of matched elements so no need to iterate a elements.

I assume that all the a elements are stored in cors .

You can set their targets before appending them to body .

Eg

$("button").click(function() {
  $.getJSON('http://anyorigin.com/get/?url=' + url + '&callback=?', function(data) {
    var $cors = $(data.contents);
    $cors.find('a').attr('target', '_blank');
    $('body').append($cors);
  });
});

Try this simple line

Old

  $("body").append(cors);
  $('body a').each(function() {
        $(this).attr('target', "_blank");
   });

Updated

 $("body").append(cors).find("a").attr('target', "_new");    

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