我正在尝试引用第二列中的对象 (object link_icon) 并基于 .json 数据,我正在分配新的 url。
我的 html 结构:
<div class="details">
<h1 id="title">title</h1>
<h3 id="author">
<a href="https://www.google.pl/">author</a>
</h3>
</div>
<a href="https://www.google.pl/">
<div><i class="link_icon"></i></div>
</a>
$(function(){
var url = 'img_and_data/' + randomNumbers[bgImgIndex] +'.json';
var title = $("#title");// the id of the heading
var author = $("#author a");// id of author
var link_icon = $(".link_icon a"); // <------- problem probably is here
$.getJSON(url, function (data) {
title.text(toTitleCase(data.title));
author.text(data.copyright);
author.attr("href", data.url);
link_icon.attr("href", data.permalink);
});
}
这是我的完整代码: https://jsfiddle.net/cvv0sen8/8/
如何引用link_icon
修改href
?
你能帮帮我吗?
JSON:
{
"title": "example title",
"copyright": "example author",
"permalink": "https://www.bing.com/",
"url": "http://www.yahoo.com"
}
最佳答案
var link_icon = $(".link_icon a");
您的选择器在这里表示“每个 a
标签都有一个带有类 link_icon
的标签作为父标签”。问题是您的 html 文档在 link_icon
中不包含任何 a
标记:您的选择器将不返回任何内容。
您可以这样更改您的 html:
<div><a class="link_a" href="#"><i class="link_icon"></i></a></div>
还有你的js:
var link_a = $(".link_a");
// ...
link_a.attr("href", data.permalink);
关于javascript - 引用第二列中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49346761/