i'm trying to display link preview on each link with jquery, but actually my code append multiple divs (one for each link in the body) instead of one for the link itself.
here the fiddle: https://jsfiddle.net/eg4zwpk9/4/
my code so far
this.$(".Post-body").find('a').each((i, e) => {
this.$('.Post-body').attr('id', 'value');
const isMobile = navigator.userAgentData.mobile;
let controller = new AbortController();
let href = e.getAttribute("href");
console.log(href)
if (isMobile === false) {
fetch(`https://preview-api.bbspace.top/?url=` encodeURIComponent(href), {
method: "GET",
mode: "cors",
signal: controller.signal,
credentials: "omit"
})
.then((res) => res.json())
.then((response) => {
console.log(response)
if (!e.text.startsWith("http")) return;
let $s = $('#value a')
let imgResp = '<img src="' response.image '" width="250">';
if (response.image === undefined) {
imgResp = '<img src="https://www.studioippocrate.com/wp-content/uploads/2017/11/pac-404.png" width="250">';
}
this.$('#value a').append('<div >\n'
' <button ><i ></i></button>\n'
' <div >\n'
' <div >\n'
' ' imgResp ''
' <div >' response.description '</div> '
' </div>\n'
' </div>\n'
'</div>');
});
}
});
how can i display only the correct result for EACH link?
CodePudding user response:
You append that preview element to all links that are inside #value. Instead of this:
this.$('#value a').append('<div >\n'
' <button ><i ></i></button>\n'
' <div >\n'
' <div >\n'
' ' imgResp ''
' <div >' response.description '</div> '
' </div>\n'
' </div>\n'
'</div>');
You have to do like this:
$(e).append('<div >\n'
' <button ><i ></i></button>\n'
' <div >\n'
' <div >\n'
' ' imgResp ''
' <div >' response.description '</div> '
' </div>\n'
' </div>\n'
'</div>');
You have there already each function which give you link element. Also there is no point to assign that id to .Post-body.
CodePudding user response:
I've copied your fiddle and corrected it
In summary, when you select your link with this.$('#value a')
before appending the new html, you are selecting all the links of the page, so it will add the new html to all your links.
To correct it, you can just convert your e
into jquery like so : $(e).append(...)