简体   繁体   English

通过函数传递elementID然后返回变量并在别处使用。 可能?

[英]Pass an elementID through a function then return variable and use elsewhere. Possible?

I'm trying to pass an element ID to a function, which then returns an edited string value to another element in my document. 我正在尝试将元素ID传递给函数,然后函数将编辑后的字符串值返回给文档中的另一个元素。 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. 示例如下:使用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>

Your code is passing the actual element into the function, rather than the ID of the element. 您的代码将实际元素传递给函数,而不是元素的ID。 It looks like this is what you need: 看起来这就是你需要的:

JavaScript function: JavaScript函数:

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM