If I click any of these a
elements:
<a href="#" id="12345">title 1</a>
<a href="#" id="67890">title 2</a>
Then it should get the id and find a match from the JSON:
entry: [{
id: {
$t: "post-12345"
},
content: {
type: "html",
$t: "content 1",
}
}, {
id: {
$t: "post-67890"
},
content: {
type: "html",
$t: "content 2",
}
}]
Then it will append the result in "content" div:
<div class="content">
content 1 OR content 2
</div>
I triend similar solution posted here but cant make it work.
CodePudding user response:
Correct you JSON format by adding quotes.
Try this:
var data = `{
"entry": [
{
"id": {
"$t": "post-12345"
},
"content": {
"type": "html",
"$t": "content 1"
}
},
{
"id": {
"$t": "post-67890"
},
"content": {
"type": "html",
"$t": "content 2"
}
}
]
}`;
var json = JSON.parse(data);
$('a').on('click',function () {
//var id = $(this).attr('id');
let full_id = 'post-' $(this).attr('id');
$.each(json['entry'], function (i, e) {
let id = json['entry'][i].id['$t'];
if (id == full_id) {
let type = json['entry'][i].content.type;
let content = json['entry'][i].content['$t'];
$('.content').html(content);
return false;
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="#" id="12345">title 1</a>
<a href="#" id="67890">title 2</a>
<div class="content">
content 1 OR content 2
</div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
CodePudding user response:
Use jQuery.on('click', handler)
as show in the following code:
$('a[id]').on('click', function() {
let id = this.id;
let content = resp.entry.filter(content => content.id.$t === `post-${id}`);
!content.length || $('div.content').text( content[0].content.$t );
});
DEMO