将 href 属性更改为从 API 和 jquery 生成的字符串
Changing href attribute to generated string from API with jquery
我想在这部分代码上更改 link 的 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));
}
但我似乎无法从外部范围访问它。
基本上我想通过在 link 末尾添加 $('.author')
名称来 link 到维基百科作者页面。
将 update.response
添加到 link 的末尾,但我得到 undefined
response
来自哪里?
您是否将其声明为全局变量?例如 var response;
如果是这样,那么只需放置此代码:
$('a').attr('href', function() {
return this.href + response; // you dont need update.response just response
});
after 无论你在哪里打电话 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);
}
您的代码中有一些错误:
- 响应来自哪里?
- 您应该在收到来自 api 的数据后更新 link href。
您可以尝试这样修改您的代码:
<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 );
});
}
我想在这部分代码上更改 link 的 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));
}
但我似乎无法从外部范围访问它。
基本上我想通过在 link 末尾添加 $('.author')
名称来 link 到维基百科作者页面。
将 update.response
添加到 link 的末尾,但我得到 undefined
response
来自哪里?
您是否将其声明为全局变量?例如 var response;
如果是这样,那么只需放置此代码:
$('a').attr('href', function() {
return this.href + response; // you dont need update.response just response
});
after 无论你在哪里打电话 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);
}
您的代码中有一些错误:
- 响应来自哪里?
- 您应该在收到来自 api 的数据后更新 link href。
您可以尝试这样修改您的代码:
<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 );
});
}