javascript 使用 EJS 或 jQuery 设置 HTML 标签的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23982709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:55:16  来源:igfitidea点击:

Setting the attribute of an HTML tag with EJS or jQuery

javascriptjqueryhtmlexpressejs

提问by Elementary

On my express server I'm rendering a page with data as follows:

在我的快速服务器上,我正在渲染一个包含数据的页面,如下所示:

app.get('/people/:personID', function (req, res) {
  res.render("people/profile", {person: req.person });
});

In my profile.ejs file I can access the data in an ejs tag like so: <p><%= person.name %></p>

在我的 profile.ejs 文件中,我可以像这样访问 ejs 标签中的数据: <p><%= person.name %></p>

I can't figure how to change an attribute of an html tag to the value stored in this object though.

我无法弄清楚如何将 html 标记的属性更改为存储在此对象中的值。

This doesn't work: <img id="my_img" src=<%= person.picture %> alt="">
or this: $("#my_img").attr("src", <%= person.picture %>);

这不起作用:<img id="my_img" src=<%= person.picture %> alt="">
或者这个:$("#my_img").attr("src", <%= person.picture %>);

Also, if there's a better way to pass this document to the html page and access it I'm all ears(or eyes in this case). Thank you

另外,如果有更好的方法将此文档传递到 html 页面并访问它,我会全力以赴(或在这种情况下是眼睛)。谢谢

回答by zishe

You have to include string values within quotes.

您必须在引号内包含字符串值。

In html:

在 HTML 中:

<img id="my_img" src="<%= person.picture %>" alt="">

In jQuery:

在 jQuery 中:

$("#my_img").attr("src", "<%= person.picture %>");