【问题标题】:How to combine these two JavaScript functions?如何组合这两个 JavaScript 函数?
【发布时间】:2010-03-15 21:24:37
【问题描述】:
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>

我需要帮助,如何将两个参数作为一个函数?这意味着当您单击时,图像和文本都会发生变化。 谢谢! 比安卡

【问题讨论】:

  • 啊,抱歉,我已尽力编辑问题。是时候下班了。

标签: javascript function arguments


【解决方案1】:
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";
  }
}

【讨论】:

    【解决方案2】:

    创建一个调用它们的新函数,并将它们重命名为独特的名称。

    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";
        }
    }
    

    这也消除了您对全局变量的依赖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多