通过函数传递 elementID,然后返回变量并在其他地方使用。可能的?

发布于 2024-12-09 04:23:54 字数 428 浏览 5 评论 0原文

我试图将元素 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

捂风挽笑 2024-12-16 04:23:54

您的代码将实际元素传递到函数中,而不是元素的 ID。看起来这就是您所需要的:

JavaScript 函数:

setLogo = function(sport){
    var img = document.getElementById("sportLogo");
    if (img){
        img.src = "images/" + sport + "-logo.png";
    }
}

标记:

<a id="soccer" onclick="setLogo('soccer');">Soccer</a>
<a id="baseball" onclick="setLogo('baseball');">Baseball</a> 
<div id="selectedsport"> 
    <img id="sportLogo" /> 
</div> 

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:

setLogo = function(sport){
    var img = document.getElementById("sportLogo");
    if (img){
        img.src = "images/" + sport + "-logo.png";
    }
}

Markup:

<a id="soccer" onclick="setLogo('soccer');">Soccer</a>
<a id="baseball" onclick="setLogo('baseball');">Baseball</a> 
<div id="selectedsport"> 
    <img id="sportLogo" /> 
</div> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文