搜尋

首頁  >  問答  >  主體

javascript - 求教為什麼這段script改寫為函數傳參形式就不執行了?

js新手,請教為什麼寫法1改寫成傳參形式的寫法2就不執行了?謝謝!
<html>

    <form id="search-bar" class="hide" action="/action_page.php">

        <input id="search-box" type="search" value="search">
        <input id="search-submit" type="submit">

    </form>
        <button id="search-but" >click me</button>

</html>

寫法1:
<script>

    var osearch = document.getElementById("search-but")
    var obar = document.getElementById("search-bar")

    osearch.onclick = function () {

        if (obar.style.display == "block") {
            obar.style.display ="none"
        }
        else {
            obar.style.display="block"
        }
    }

</script>

寫法2:
<script>

function display(obj) {

    var b = document.getElementById("obj")

    if (b.style.display == "block") {
        b.style.display = "none"
    }
    else {
        b.style.display = "block"
    }
}

var osearch = document.getElementById("search-but")

 osearch.onclick=display(search-bar);

</script>

PHPzPHPz2757 天前533

全部回覆(2)我來回復

  • 滿天的星座

    滿天的星座2017-05-19 10:35:40

    function display(obj) {
    
        var b = document.getElementById(obj)
    
        if (b.style.display == "block") {
            b.style.display = "none"
        }
        else {
            b.style.display = "block"
        }
    }
    
    var osearch = document.getElementById("search-but")
    
     osearch.onclick=function () { display('search-bar'); }

    基礎不紮實啊

    回覆
    0
  • 阿神

    阿神2017-05-19 10:35:40

    回覆
    0
  • 取消回覆