javascript onclick更改onclick到新功能

时间:2013-12-12 16:03:26

标签: javascript html onclick

我需要能够更改id的onclick事件,以便在执行更改onclick事件的函数后单击它一次

这是我的代码: 使用Javascript:

function showSearchBar()
    {
        document.getElementById('search_form').style.display="inline";
        document.getElementById('searchForm_arrow').onclick='hideSearchBar()';
    }

    function hideSearchBar()
    {
        document.getElementById('search_form').style.display="none";
        document.getElementById('searchForm_arrow').onclick='showSearchBar()';
    }

这是HTML:

<!-- Search bar -->
<div class='search_bar'>
    <img id='searchForm_arrow' src="images/icon_arrow_right.png" alt=">" title="Expand" width="10px" height="10px" onclick='showSearchBar()' />
    <form id='search_form' method='POST' action='search.php'>
        <input type="text" name='search_query' placeholder="Search" required>
        <input type='image' src='images/icon_search.png' style='width:20px; height:20px;' alt='S' >
    </form>
</div>

由于

7 个答案:

答案 0 :(得分:2)

在两个地方更改代码以直接引用新功能,例如:

document.getElementById('searchForm_arrow').onclick=hideSearchBar;

答案 1 :(得分:2)

你能试试吗,

      function showSearchBar()
        {
            if(document.getElementById('search_form').style.display=='none'){
                 document.getElementById('search_form').style.display="inline";
            }else{
               document.getElementById('search_form').style.display="none";
            }

        }

答案 2 :(得分:0)

你几乎是对的。您正在将onclick设置为字符串而不是函数。尝试:

showSearchBar()中的

 document.getElementById('searchForm_arrow').onclick=hideSearchBar;
在hideSearchBar()

 document.getElementById('searchForm_arrow').onclick=showSearchBar;

答案 3 :(得分:0)

您不需要创建两个功能。 只需创建一个函数并使用if条件,您就可以显示和隐藏表单标记..

function showSearchBar()
        {
            if(document.getElementById('search_form').style.display=='none'){
                 document.getElementById('search_form').style.display=''; // no need to set inline
            }else{
               document.getElementById('search_form').style.display='none';
            }

        }

答案 4 :(得分:0)

使用javascript,您可以检查并执行操作

function SearchBarevent()
        {
            if(document.getElementById('search_form').style.display=='none'){
                 document.getElementById('search_form').style.display="inline";
            }else{
               document.getElementById('search_form').style.display="none";
            }

        }

或者如果您可以使用jquery,则可以使用更好的解决方案toogle

喜欢:

$("#button_id").click(function(){
$( "#search_form" ).toggle( showOrHide );
});

Fiddle就是示例

答案 5 :(得分:0)

function searchBar(){
    var x = document.getElementById('search_form').style.display;
    x = (x == 'inline') ? 'none' : 'inline';
}

通过添加对元素当前条件的检查并根据该条件应用样式,可以将两个函数合并为一个。实际上并没有改变功能但不需要,因为现在只有一个功能执行这两个动作。

答案 6 :(得分:0)

这是一个使用jQuery的选项:

$('#searchForm_arrow').click(function() {
    $('#search_form').slideToggle();
});

http://jsfiddle.net/PuTq9/