Javascript function is the right way to do it

Hi everyone and thanks for watching,

What is the correct way to do this:

<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 image name scotislands.jpg

Thanks a lot B.

+3
source share
5 answers

The following line lists your string identifiers:

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 remarked, there onClick="flag(scotislands)";should beonClick="flag('scotislands')";

+2
source

You need to quote the text in the link tag, otherwise it will try to find and not find the variable with the name scotislands.

 onClick="flag('scotislands');"

then change the innerHTML assignment to the following:

 document.getElementById("flag").innerHTML="<img src='images/flags/" + nation + ".jpg'>"

URL, .

, - ( ). , jQuery, - :

 <a href="#scotislands" class="flag-identifier">Scotislands</a>

, javascript, :

 $(function() {
     $('a.flag-identifier').click( function() {
         var flag = $(this).attr('href').replace('#','');
         $('#flag').html( '<img src="images/flags/' + flag + '.jpg" />' );
         return false;
     });
 });

, href , flag , URL- . , nation, , .

0

, innerHTML, . :

document.getElementById("flag").innerHTML="<img src='images/flags/'+nation+'.jpg'>";

, onClick , "scotislands". :

onClick="flag('scotislands');"
0
source
function flag(nation) {
  var myFlag = document.getElementById("flag").getElementsByTagName("img")[0];
  myFlag.src = "images/flags/"+nation+".jpg";
}
0
source

It depends on what you mean by "right." I suspect that you are using innerHTMLthat you do not mean “conforming to a recognized standard, such as the DOM,” but this is what you get 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);
}
0
source

Source: https://habr.com/ru/post/1731023/


All Articles