简体   繁体   中英

How can I pass an innerText of HTML element as object key?

So I have an API for movies, and I have a button which should display movies of particular genre when clicked. For example, button is something like this:

<span>action</span>

And my API url looks something like this: https://api.themoviedb.org/3/discover/movie?api_key={api_key}&sort_by=popularity.desc&with_genres=80&page=4

So as you see, I should insert to with_genres param any other genre number, so I wrote a function for it:

function genreChoose(e){
        let genres = {
            action: 80
        }
        let url = new URL(lastUrl);
        url.searchParams.set('with_genres', genres.action)
        fetchURL(url);
    }

I made an object of genres, and when I click on genre <span> from above, it should pass innerText as object key, so a text in span and key in genres object are both "action". I guess doing it like url.searchParams.set('with_genres', genres.e.innerText) doesn't work, so I'm looking for a way to pass innerText of <span> as object value.

For example:

 const button = document.querySelector('button'); function genreChoose(e) { let genres = { action: 80 }; let url = new URL('https://api.themoviedb.org/3/discover/movie'); url.searchParams.set('with_genres', genres[e.target.innerText]); console.log(url); } button.addEventListener('click', genreChoose);
 <button>action</button>

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