通过函数传递 elementID,然后返回变量并在其他地方使用。可能的?
我试图将元素 ID 传递给函数,然后该函数将编辑后的字符串值返回到文档中的另一个元素。这可以做到吗?
下面的例子: 使用 onclick 事件获取“soccer”的 elementID,将其传递给函数以添加前缀/后缀,然后将该结果传递给文档中的另一个部分。
function sportlogo(logo) {
var logo = "images/" + logo + "-logo.png";
return logo;
}
<a id="soccer" href="#selectedsport" onclick="sportlogo(document.getElementById('soccer'))">
<div id="selectedsport">
<img src=logo;/>
</div>
I'm trying to pass an element ID to a function, which then returns an edited string value to another element in my document. Can this be done?
Example below:
grab the elementID of 'soccer' using onclick event, pass that to the function to add prefix/suffix, then pass that result to another section in the document.
function sportlogo(logo) {
var logo = "images/" + logo + "-logo.png";
return logo;
}
<a id="soccer" href="#selectedsport" onclick="sportlogo(document.getElementById('soccer'))">
<div id="selectedsport">
<img src=logo;/>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码将实际元素传递到函数中,而不是元素的 ID。看起来这就是您所需要的:
JavaScript 函数:
标记:
Your code is passing the actual element into the function, rather than the ID of the element. It looks like this is what you need:
JavaScript function:
Markup: