大家好,第一次在这里提问。那么我们开始吧。我有一个带有 json 返回的 ajax 请求。我现在尝试获取响应并动态创建菜谱标题,同时还使用响应数据创建 a href。
$( window ).load( function() {
$.get({
url: window.location.href + ".json"
}).success( function( response ) {
console.log( response );
let $title = $( ".js-title" );
let reviewCount = 0;
while( reviewCount < $title.length ) {
let recipe_title = response[reviewCount].recipe.title;
let href = response[reviewCount].location.href;
$title[reviewCount].prepend( `<a>${ recipe_title }</a>` ).attr('href', `${ href }`);
reviewCount++;
}
});
});
我无法弄清楚 href 部分。
最佳答案
可以在模板中添加href(创建元素时),无需使用attr函数。
支持上述陈述的示例片段:
function prepend() {
let title = 'something';
let href = 'something/else'
$('div').append(`<a href='${href}'>${title}</a>`)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>
致用户立场您所做的事情有什么问题:
毫无疑问,jQuery prepend 方法是可链接的,但它将返回它所应用的元素。因此,如果您打开检查器,您应该会看到 href 已添加到 $title[reviewCount]
元素中。
要正确执行此操作,您需要构造 a 元素,然后将其添加到前面。
示例片段。
function prepend() {
let title = 'something';
let href = 'something/else';
$('div').prepend($('<a></a>').text(`${title}`).attr('href', `${href}`))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>
在特定元素前面添加:
我们需要使用eq Jquery 的方法,同样这是可实现的。
用途:
$title.eq(reviewCount).prepend($('<a>').text(`${ response[reviewCount].recipe.title }`).attr('href', http: //localhost:3000/recipes/`${recipe_id}`));
关于javascript - 如何在 html 标签 href 中使用 es6 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44103423/