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. 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>
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>
精彩评论