Если вы измените часть HTML / PHP на своей странице, добавив в нее простую гиперссылку, например:
<p>Here are all the jokes in the database:</p>
<?php foreach ($jokes as $id => $joke): ?>
<blockquote>
<p>
<?php
echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');
?>
</p>
<a class='download' href='#' title='Download the joke'>Download</a>
</blockquote>
<?php endforeach; ?>
Затем скопируйте нижеприведенный javascript на свою страницу и обнаружите, что вы можете загрузитьшутки по желанию.Если вы скопируете весь приведенный ниже код, вы обнаружите, что он будет работать в вашем браузере нормально.
<html>
<head>
<title>Download a joke</title>
<script>
/*
wait for the DOM to load and then set event listeners
on the new hyperlinks
*/
document.addEventListener('DOMContentLoaded', ()=>{
/*
Query the DOM for ALL hyperlinks of class `download`
and assign an event handler for click events
*/
document.querySelectorAll('a.download').forEach( function(a){
a.addEventListener( 'click', function( event ){
/*
prevent the default action for this hyperlink
*/
event.preventDefault();
/*
The Joke is located in the previous
DOM node - P
*/
let p=this.previousElementSibling;
/*
create a BLOB object to store the joke text
*/
let blob=new Blob([ p.innerText ],{type: 'text/plain'});
/*
function to send the file - jiggery pokery
*/
const sendfile=function( blob, name ){
let url=URL.createObjectURL( blob );
let lnk=document.createElement('a');
let evt=new MouseEvent('click',{
bubbles:true,
cancelable:true,
view:window
});
p.appendChild( lnk );
lnk.href=url;
lnk.download=name;
lnk.dispatchEvent( evt );
p.removeChild( lnk );
}
sendfile.call( this, blob, 'joke.txt' );
});
});
});
</script>
</head>
<body>
<!-- EXAMPLE DATA -->
<blockquote>
<p>
This is the joke - not very funny though is it?
</p>
<a class='download' href='#' title='Download the joke'>Download</a>
</blockquote>
<blockquote>
<p>
This is another joke - or what passes for a joke!
</p>
<a class='download' href='#' title='Download the joke'>Download</a>
</blockquote>
<blockquote>
<p>
This is probably not the best joke in the World.
</p>
<a class='download' href='#' title='Download the joke'>Download</a>
</blockquote>
<blockquote>
<p>
A woman gets on a bus with her baby. The bus driver says: 'Ugh, that's the ugliest
baby I've ever seen!' The woman walks to the rear of the bus and sits down, fuming.
She says to a man next to her: 'The driver just insulted me!' The man says: 'You go
up there and tell him off. Go on, I'll hold your monkey for you.
</p>
<a class='download' href='#' title='Download the joke'>Download</a>
</blockquote>
</body>
</html>