javascript function - the correct way to do this
Hi all and thanks for looking,
What is the correct way to do this:
&l开发者_运维知识库t;script language="javascript">
function flag(nation)
{
this.nation=nation;
document.getElementById("flag").innerHTML="<img src='images/flags/'+nation+'.jpg'>";
}
</script>
with this in the link tags: onClick="flag(scotislands)"; and the image name being scotislands.jpg
Many thanks, B.
In the following line you have your string identifiers mixed up:
document.getElementById("flag").innerHTML="<img src='images/flags/'+nation+'.jpg'>";
It should be:
document.getElementById("flag").innerHTML='<img src="images/flags/'+nation+'.jpg">';
EDIT
Also, as Joel spotted, onClick="flag(scotislands)";
should be onClick="flag('scotislands')";
You need to quote the text in the link tag, otherwise it tries and fails to find a variable with the name scotislands
.
onClick="flag('scotislands');"
then change the assignment of the innerHTML to the following:
document.getElementById("flag").innerHTML="<img src='images/flags/" + nation + ".jpg'>"
Note the use of single quotes internally to set of the url, but double quotes around each of the inline text bits.
Generally, though, I'd prefer something unobtrusive (no code in markup). Using a framework, such as jQuery, I'd do something like:
<a href="#scotislands" class="flag-identifier">Scotislands</a>
Then using javascript, I'd add a handler for all such links:
$(function() {
$('a.flag-identifier').click( function() {
var flag = $(this).attr('href').replace('#','');
$('#flag').html( '<img src="images/flags/' + flag + '.jpg" />' );
return false;
});
});
This would add a click handler that gets the flag name from the href on the anchor, then replaces the named element flag
's content with the image constructed by adding the name of the country to the image url. Note that I omitted the global variable nation
, but you could easily set it from within the click handler as well if necessary.
The string that you are setting innerHTML to is not quoted properly. Try this:
document.getElementById("flag").innerHTML="<img src='images/flags/'+nation+'.jpg'>";
Also, your onClick is trying to send an non-existent object called "scotislands". Try this instead:
onClick="flag('scotislands');"
function flag(nation) {
var myFlag = document.getElementById("flag").getElementsByTagName("img")[0];
myFlag.src = "images/flags/"+nation+".jpg";
}
It depends what you mean by "correct". I suspect from the fact you're using innerHTML
that you don't mean "conforming to a recognised standard, such as DOM", but that's what you're getting from me:
function flag(nation) {
var flagEl = document.getElementById("flag");
while (flagEl.firstChild) {
flagEl.removeChild(flagEl.firstChild);
}
var img = document.createElement("img");
img.src = "images/flags/" + nation + ".jpg";
flagEl.appendChild(img);
}
精彩评论