[英]Changing href attribute to generated string from API with jquery
我想在代碼的這一部分更改鏈接的href
屬性
<a href="https://en.wikipedia.org/wiki/" class="author" target="_BLANK"></a>
我正在使用此代碼更改href屬性
$('a').attr('href', function() {
return this.href + update.response;
});
我試圖在這個函數中做一個變量
function update(response) {
$('#response').html(JSON.stringify(response.quoteText));
var okay = $('.author').html(JSON.stringify(response.quoteAuthor));
}
但是我似乎無法從外部范圍訪問它。
基本上,我想通過在鏈接末尾添加$('.author')
名稱鏈接到Wikipedia作者頁面。 在鏈接末尾添加了update.response
,但是我不確定
response
來自哪里?
您是否將其聲明為全局變量? 例如var response;
如果是這樣,則只需放置以下代碼:
$('a').attr('href', function() {
return this.href + response; // you dont need update.response just response
});
無論您在哪里調用update();
只要在收到回應時更新href。
例如。
http://codepen.io/anon/pen/rrJYbJ
var a = $('a'),
wiki = a.attr('href');
function update(response) {
$('#response').html(JSON.stringify(response.quoteText));
$('.author').html(JSON.stringify(response.quoteAuthor));
a.attr('href',wiki + response.quoteAuthor);
}
您的代碼中有一些錯誤:
您可以嘗試更改代碼,如下所示:
<a href="https://en.wikipedia.org/wiki/" data-base-href="https://en.wikipedia.org/wiki/" class="author" target="_BLANK"></a>
和js:
function update(response) {
$('#response').html(JSON.stringify(response.quoteText));
$('.author').html(JSON.stringify(response.quoteAuthor));
$('a').each( function () {
var newHref = $(this).data('data-base-href')+response.quoteAuthor;
$(this).attr('href',newHref );
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.