Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - pass parameter to href

i'm need to pass parameter to href base on the firstname on the list, the name is a link to aonther page that i get via _id that pass on the url .

the issue is that the id dont pass to the url and i get an error

how can i pass data to the url ?

my code :

<script>
    const getuser = () => {
        pers.forEach(per => {
            if (document.getElementById("link") == per.FirstName) {
                document.getElementById("link").setAttribute("href","/persons/"+per._id);
            }
        })
    }

</script>

<body>
    <h1>Persons</h1>
    <ul>
        <% pers.forEach(function(per) { %>

            <li>
                <a  id="link" onclick="getuser()">
                    <%= per.FirstName %>
                </a>
            </li>

            <% }) %>

    </ul>
question from:https://stackoverflow.com/questions/66060253/pass-parameter-to-href

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This

if (document.getElementById("link") == per.FirstName) {

Will never evaluate true. You're comparing a reference to an HTML element to a (I presume) string FirstName.

I can't fathome why you're trying to do this in javascript when you are server-side rendering the page. Just build the HTML inline

<ul>
    <% pers.forEach(function(per) { %>
        <li>
            <a href="/persons/<%= per.Id%>">
                <%= per.FirstName %>
            </a>
        </li>
    <% }) %>
</ul>

Note: Removed Id from your element as ids should be unique and you're rendering in a loop!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...