[英]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. 我想补充target="_new"
每a
附加一些内容到DOM后标签,但我不是成功的。
Please run the snippet and click " Go CORS Go ", wait until the content is fully loaded and try to click on the duck. 请运行代码段 ,然后单击“ Go CORS Go ”,等待内容完全加载,然后尝试单击鸭子。 Despite being an a
tag, the new attribute doesn't seem to work. 尽管是a
标签,新的属性似乎并没有工作。 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 编辑ajax结果,而不是附加后的页面结果
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
由ajax返回的响应具有导致错误的脚本, ReferenceError: DDG is not defined(…)
,该脚本将在ReferenceError
之后暂停语句的执行
Place your .append
statement in try..catch
hence error will not affect your later script. 将您的.append
语句放入try..catch
因此错误不会影响您以后的脚本。
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. 更新:由于在提出意见, .attr( attributeName, value )
设置一个或多个属性为匹配的元素集合所以没有必要重复的 a
元素。
I assume that all the a
elements are stored in cors
. 我假设所有a
元素都存储在cors
。
You can set their targets before appending them to body
. 您可以在将它们附加到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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.