[英]Change a target attribute with jQuery
我想補充target="_new"
每a
附加一些內容到DOM后標簽,但我不是成功的。
請運行代碼段 ,然后單擊“ Go CORS Go ”,等待內容完全加載,然后嘗試單擊鴨子。 盡管是a
標簽,新的屬性似乎並沒有工作。 有什么見解嗎?
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>
編輯ajax結果,而不是附加后的頁面結果
嘗試以下方法:
var newcors = $(cors).find('a').attr('target', "_blank").end();
$('body').append(newcors);
由ajax返回的響應具有導致錯誤的腳本, ReferenceError: DDG is not defined(…)
,該腳本將在ReferenceError
之后暫停語句的執行
將您的.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>
更新:由於在提出意見, .attr( attributeName, value )
設置一個或多個屬性為匹配的元素集合所以沒有必要重復的 a
元素。
我假設所有a
元素都存儲在cors
。
您可以在將它們附加到body
之前設置它們的目標。
例如
$("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);
});
});
試試這條簡單的線
舊
$("body").append(cors);
$('body a').each(function() {
$(this).attr('target', "_blank");
});
更新
$("body").append(cors).find("a").attr('target', "_new");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.