1

我在Javascript中编写了一个调用jQuery函数的简单函数问题是为什么我需要单击按钮来获得切换效果

html

<input id="toggle" type="button" value="Toggle" onclick="toggle()" />

javascript

<script type="text/javascript">
function toggle()
{
    new_toggle();
}
</script>

jQuery

$(function new_toggle2(){
        $('#toggle').click(function(){

    $('#p1').toggle(); // Simple <p> and <h1> tags
            $('#h').toggle();   
        });
    new_toggle = new_toggle2;
});
4

4 回答 4

1

我相信这对于点击事件来说已经足够了。

HTML:

<input id="toggle" type="button" value="Toggle" />

JS:

$(function(){
        $('#toggle').click(function(){

            $('#p1').toggle(); // Simple <p> and <h1> tags
            $('#h').toggle();   
        });
});
于 2012-10-11T14:19:04.333 回答
1

You have this code with you:

<input id="toggle" type="button" value="Toggle" onclick="toggle()" />

The toggle() is the function, which should be initiated. That function is bound to the <input> tag with the help of onclick= attribute. The onclick event is used to execute a JavaScript when an element is clicked.

If you want to trigger that function on page load, then a small change is required. The toggle() function should be called when the document loads.

$(document).ready(function () {
    toggle();
}
于 2012-10-11T14:20:47.427 回答
1

I think you're a little bit confused about it...

Remove:

onclick="toggle()"

and:

<script type="text/javascript">
function toggle()
{
    new_toggle();
}
</script>

And write just this:

$(function(){
    $('#toggle').click(function(){

        $('#p1').toggle();
        $('#h').toggle();   
    });
});
于 2012-10-11T14:21:58.753 回答
0

Reading a lot into your question! - If you want your toggle function to fire on page load, rather than when you click the button change your function to:

<script type="text/javascript">
    $(document).ready(function () {
            new_toggle2();
    }
</script>
于 2012-10-11T14:20:44.507 回答