开发者

How to combine these two JavaScript functions?

var curtext = "View large image";
function changeSrc() {
    if (curtext == "View large image") {
        document.getElementById("boldStuff").innerHTML = "View small image";
        curtext="View small image";
    } else {
        document.getElementById("boldStuff").innerHTML = "View large image";
        curtext = "View large image";
    }
}

var curimage = "cottage_small.jpg";
function changeSrc() {
    if (curimage == "cottage_small.jpg") {
        document.getElementById("myImage").src = "cottage_large.jpg";
        curimage = "cottage_large.jpg";
    } else {
        document.getElementById("myImage").src = "cottage_small.jpg";
        curimage = "cottage_small.jpg";
    }
}
</script>
</head>

<body>
<开发者_开发知识库;!-- Your page here -->
<h1> Pink Knoll Properties</h1>
<h2> Single Family Homes</h2>

<p> Cottage:<strong>$149,000</strong><br/>
    2 bed, 1 bath, 1,189 square feet, 1.11 acres <br/><br/>
 <a href="#" onclick="changeSrc()"><b id="boldStuff" />View large image</a></p>  
 <p><img id="myImage" src="cottage_small.jpg" alt="Photo of a cottage"  /></p> 
</body>

I need help, how to put as one function with two arguments? That means when you click, the image and text both will be change. Thank you! Bianca


function combined(curtext, curimage){
  if(curtext == "View large image"){
      document.getElementById("boldStuff").innerHTML = "View small image";
        curtext="View small image"; 
      }
      else{
       document.getElementById("boldStuff").innerHTML= "View small image";
           curtext="View large image";    
  }
  if(curimage == "cottage_small.jpg"){
       document.getElementById("myImage").src="cottage_large.jpg";
       curimage="cottage_large.jpg";
        }
      else{
       document.getElementById("myImage").src="cottage_large.jpg";    
       curimage="cottage_small.jpg";
  }
}


Make a new function that calls them both, and rename them to something unique.

var changeCombined = function() {
    changeTxt();
    changeSrc();
};

function changeTxt() {
    var node = document.getElementById("boldStuff");

    if ( node.innerHTML == "View large image") {
        node.innerHTML = "View small image";
    } else {
        node.innerHTML = "View large image";
    }
}

function changeSrc() {
    var image = document.getElementById("myImage");

    if ( image.src == "cottage_small.jpg") { 
        image.src = "cottage_large.jpg";
    } else {
        image.src = "cottage_small.jpg";
    }
}

This also removes your dependency on globals.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜