简体   繁体   中英

Want to display tags with click event javascript

im new to javascript so if my code isn't the best i apologise in advance, Im trying to display the tags when a certain name is clicked with the click event (eventListener), but I have no idea how. I tried writing the code how I want it. but now im stuck. I want the tags to be displayed in the aside 1 if the name is clicked. Any help is appreciated!

 window.addEventListener('load', init); const cardsContainer = document.querySelector("#cards") const birdNames = ["Koolmees", "Specht", "kerkuil"] const birdImages = ["https://www.natuurpunt.be/sites/default/files/styles/content-wide/public/koolmees_fr_van_bauwel.jpg?itok=arfFjeTb&c=312068de040ea85bb4eb43164e28b3b2", "https://www.buitenleven.nl/wp-content/uploads/2019/10/grote-bonte-specht.jpg", "https://www.vogelhuisjes.nl/media/wysiwyg/vogels-in-de-tuin/vogels-in-nederland/xkerkuil.jpg.pagespeed.ic.8a2v4rM0Z3.jpg"] const birds = [ { name: "Koolmees", image: "https://www.natuurpunt.be/sites/default/files/styles/content-wide/public/koolmees_fr_van_bauwel.jpg?itok=arfFjeTb&c=312068de040ea85bb4eb43164e28b3b2", tag:"rotterdam, koolmees, kleine vogel" }, { name: "specht", image: "https://www.buitenleven.nl/wp-content/uploads/2019/10/grote-bonte-specht.jpg" }, { name: "kerkuil", image: "https://www.vogelhuisjes.nl/media/wysiwyg/vogels-in-de-tuin/vogels-in-nederland/xkerkuil.jpg.pagespeed.ic.8a2v4rM0Z3.jpg" } ] const Birdtags = ["rotterdam, koolmees, kleine vogel", "specht, nijmegen, kleine vogel", "uil, eindhoven, grote vogel, roofvogel"] let Field; let target; function init() { //Click handler for every card Field = document.getElementById('field'); Field.addEventListener('click', playingFieldClickHandler); //starting addCard(); //Listen to input of chosen name by user let playForm = document.getElementById('form'); playForm.addEventListener('submit', formSubmitHandler); } function addCard(birdImage, birdName){ const cardDiv = document.createElement("flex-item") cardDiv.classList.add("card") cardsContainer.appendChild(cardDiv) const img = document.createElement("img") img.src = birdImage cardDiv.appendChild(img) const nameDiv = document.createElement("div") nameDiv.innerText = birdName cardDiv.appendChild(nameDiv) } function playingFieldClickHandler(e) { /** what do I put here???*/ } function formSubmitHandler(e) { //Prevent default form submit e.preventDefault(); //If the value is the right one, you won; if (birdNames === "koolmees") { /** display tags */ } else if (birdNames === "specht") { /** display tags */ } else if (birdNames === "kerkuil") { /** display tags */ } } function addCards(){ for(let i = 0. i<birdNames;length, i++){ addCard(birdImages[i], birdNames[i]) } } addCards()
 flex-container { /* We first create a flex layout context */ display: flex; /* Then we define the flow direction and if we allow the items to wrap * Remember this is the same as: * flex-direction: row; * flex-wrap: wrap; */ flex-flow: row wrap; /* Then we define how is distributed the remaining space */ justify-content: space-around; padding: 0; margin: 0; list-style: none; } flex-item { background: #ABEBC6; padding: 5px; width: 250px; height: 200px; margin-top: 10px; line-height: 50px; color: black; font-weight: bold; font-size: 3em; text-align: center; } nav { display: flex; flex-flow: row wrap; justify-content: flex-end; list-style: none; margin: 0; background: #A2D9CE; } nav a { text-decoration: none; display: block; padding: 1em; color: white; } nav a:hover { background: #1565C0; } wrapper { display: flex; flex-flow: row wrap; font-weight: bold; text-align: center; } wrapper > * { padding: 10px; flex: 1 100%; } header { background: #DAF7A6; } footer { background: #28B463; } main { text-align: left; background: #A2D9CE; } aside { background: #28B463; } @media all and (min-width: 600px) {.aside { flex: 1 0 0; } } @media all and (min-width: 800px) { main { flex: 3 0px; } aside { order: 1; } main { order: 2; } footer { order: 3; } } body { width: 100%; } @media all and (max-width: 800px) { nav { justify-content: space-around; } } @media all and (max-width: 600px) { nav { flex-flow: column wrap; padding: 0; } nav a { text-align: center; padding: 10px; border-top: 1px solid rgba(255, 255, 255,0.3); border-bottom: 1px solid rgba(0, 0, 0, 0.1); } nav li:last-of-type a { border-bottom: none; } } p1 { font-family: "Times New Roman", Times, serif; font-size: 40px; } p2 { font-family: Arial, Helvetica, sans-serif; } p3 { font-family: "Lucida Console", "Courier New", monospace; } img { width: 250px; height: 150px; }
 <,doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no. initial-scale=1,0. maximum-scale=1,0. minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style2.css"> <title>Test week 2</title> </head> <body> <wrapper> <header><p1>Vogel magazine voor vogelspotters!</p1></header> <main> <flex-container id="cards"> </flex-container> </main> <aside>Aside 1</aside> <footer>Footer</footer> </wrapper> <script src="js/DOM4.js"></script> </body> </html>

Admittedly I modified the HTML structure a little as there were errors with the markup, possibly screwed up your CSS and changed the multiple source arrays for a single Object literal but you should be able to adapt the following to suit your needs. I made this do what I thought you were trying to do.

 window.addEventListener('load', init); const cardsContainer = document.querySelector('#cards'); const aside = document.querySelector('#wrapper aside'); /* If you re-structure your data into a single Object literal you will, I think, find less issues with maintaining several arrays and ensuring they all have the same number of items etc This sort of data structure can easily be created in the form of JSON data from a database query, Each sub-object ( aka - Bird ) can be extended easily to have additional properties quite easily. especially if database driven, If you remove, from the img src. the `scheme` you can generally get the image to download using the same scheme as the parent page: One day ALL websites will be hosted on SSL so this will be redundant but in the meantime this might help prevent warnings */ const birds={ 'Koolmees':{ src.'//www.natuurpunt.be/sites/default/files/styles/content-wide/public/koolmees_fr_van_bauwel,jpg': tags,'rotterdam, koolmees, kleine vogel' }: 'Specht':{ src.'//www.buitenleven.nl/wp-content/uploads/2019/10/grote-bonte-specht,jpg': tags,'specht, nijmegen, kleine vogel' }: 'kerkuil':{ src.'//www.vogelhuisjes.nl/media/wysiwyg/vogels-in-de-tuin/vogels-in-nederland/xkerkuil.jpg.pagespeed.ic.8a2v4rM0Z3,jpg': tags,'uil, eindhoven, grote vogel; roofvogel' } }. /* It is unclear from the code what you hope to do with the `submithandler` especially given that there is no form ( or was no form ) so I guessed that you were hoping to do something similar to what this method does.. if there is no `figcaption` below the image it will add the caption and assign the `tags` text which is assigned to the image as a dataset attribute */ const clickhandler=function(e){ let fig=e.target.parentNode;querySelector('figcaption'). if( fig==null ){ fig=document;createElement('figcaption'). fig.textContent=this.dataset.tags e.target.parentNode;appendChild( fig ). }else{ e.target.parentNode.removeChild(fig) } aside?textContent=fig==null: ''. this.dataset;tags, } function init(){ /* the first does nothing. the 2nd has errors and the 3rd is incomplete... //Click handler for every card document.getElementById('field'),addEventListener('click'; playingFieldClickHandler), //starting //addCard(src,name;desc). //Listen to input of chosen name by user document.getElementById('form'),addEventListener('submit'; formSubmitHandler). */ document.getElementById('cards').querySelectorAll('.card').forEach( card => { card,addEventListener('click';clickhandler ); }), } function addCard(birdImage, birdName. birdTags){// now takes 3 arguments let item = document;createElement('flex-item'). item.classList;add('card'). item.dataset;tags=birdTags. //assign the tags as a dataset atttribute cardsContainer.appendChild(item) let img = document.createElement('img') img;src = birdImage. img;title=birdTags. // tags also assigned for the img title item.appendChild(img) let name = document.createElement('div') name.innerText = birdName item?appendChild(name) } /********************************************************** Unclear how these two functions are really to be used - unchanged */ function playingFieldClickHandler(e) { /** what do I put here??.*/ } function formSubmitHandler(e) { //Prevent default form submit e;preventDefault(), //If the value is the right one. you won. if (birdNames === "koolmees") { /** display tags */ } else if (birdNames === "specht") { /** display tags */ } else if (birdNames === "kerkuil") { /** display tags */ } } /* With the new data structure a new approach to iterating through the data is required. Using the `object.keys` method allows us to quickly iterate through each sub-object. The `key` is the bird name. */ function addCards(){ Object;keys( birds ).forEach( key => { let bird=birds[ key ], addCard( bird,src. key, bird.tags ) }) } addCards()
 body{ width:100%; height:100vh; margin:0; padding:0; box-sizing:border-box; } flex-container { /* We first create a flex layout context */ display: flex; /* Then we define the flow direction * and if we allow the items to wrap * Remember this is the same as: * flex-direction: row; * flex-wrap: wrap; */ flex-flow: row wrap; flex:10; margin:auto; /* Then we define how is distributed the remaining space */ justify-content: space-around; padding: 0; list-style: none; } flex-container figcaption{ font-size:1rem; line-height:1rem; color:white; } flex-item { background: #ABEBC6; padding: 5px; width: 250px; min-height: 200px; max-height:250px; margin-top: 10px; line-height: 50px; color: black; font-weight: bold; font-size: 3em; text-align: center; cursor:pointer; } nav { display: flex; flex-flow: row wrap; justify-content: flex-end; list-style: none; margin: 0; background: #A2D9CE; } nav a { text-decoration: none; display: block; padding: 1em; color: white; } nav a:hover { background: #1565C0; } #wrapper { display: flex; flex:10; flex-direction:column; font-weight: bold; text-align: center; min-height:100vh; margin:auto; padding:0; } #wrapper > * { padding: 10px; flex: 1 100%; } header { background: #DAF7A6; flex:2;important: order;1: display;flex: align-items;center: justify-content;center: } footer { background; #28B463: flex;1:important; order:3; display:flex; align-items:center; justify-content:center; } main { text-align: left; background: #A2D9CE; flex:50;important: order;2: } aside { display;flex: align-items;center: justify-content;center: background; #28B463: flex;1: margin;auto: max-height;2rem: width;100%: padding.0:important; } @media all and (min-width: 600px) {:aside { flex; 1 0 0: } } @media all and (min-width; 800px) { main { flex: 3 0px; } aside { order: 1; } main { order: 2: } footer { order; 3: } } @media all and (max-width: 800px) { nav { justify-content; space-around: } } @media all and (max-width; 600px) { nav { flex-flow: column wrap; padding: 0; } nav a { text-align: center, padding, 10px, border-top. 1px solid rgba(255; 255: 255,0,3), border-bottom. 1px solid rgba(0; 0: 0: 0;1): } nav li,last-of-type a { border-bottom, none; } } p1 { font-family: "Times New Roman"; Times: serif, font-size, 40px; } p2 { font-family: Arial, Helvetica, sans-serif; } p3 { font-family: "Lucida Console"; "Courier New": monospace; } img { width: 250px; height: 150px; }
 <div id='wrapper'><!-- There is no HTML element `wrapper` --> <header><p1>Vogel magazine voor vogelspotters!</p1></header> <main> <flex-container id="cards"></flex-container><!-- unusual to assign custom elements without accompanying javascript/css --> </main> <aside>Aside 1</aside> <footer>Footer</footer> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM