0

パラメータ付きの関数を作りたいです。以下のコードで作業していますが、機能していません。誰が私が間違っているのか教えてください。

<head>
    <script type="text/javascript" src="jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(function hide(fn){
            $(fn).click(function(){
                $('div').hide()
            })
        })
    </script>
    <style>
        div { width:500px; height:500px; background:#FF0000; }
    </style>
</head>
<body>
    <button onclick="hide(this)">click for hide</button>
    <a href="#">click</a>
    <button>click</button>
    <div></div>
</body>
4

3 に答える 3

1

1 つの重要な点:控えめな JavaScriptを作成する必要があります。これはベスト プラクティスと見なされているためです。これにより、コンテンツとコードの分離を維持できます。したがって、最初のステップは、要素のそのonclickハンドラーを削除することです。<button>

「クリックして非表示」というボタンをクリックして、を非表示にすることを想定しています<div>。では、スケルトン コードを に取り込んでみましょう<script>

$(document).ready(function() {
    $(<button>).click(function() {
        $(<div>).hide();
    });
});

しかし、どうにかしてそのclickハンドラーをそのボタンにリンクし、そのhide関数を実際の にリンクする必要がありますdiv。これを行う最も簡単な方法は次のとおりです。自分<button><div>いくつかの ID を指定します。まあ言ってみれば...

<button id="hide-button">...</button>
<div id="hide-div">...</div>

ここで、スケルトン コードにいくつかの変更を加える必要があります。

$("#hide-button").click(function() {
    $("#hide-div").hide();
});

この単純なコードが行うことは次のとおりです。DOM が読み込まれると、名前のない関数 (その場で定義する関数に名前を付けることはできません*) がドキュメントの ready イベントから呼び出されます。clickこの名前のない関数はハンドラーをボタンにアタッチし#hide-button、ボタンをクリックすると別の無名関数が呼び出されるようにします。その関数はhide、すべてのブラウザーで機能する jQuery マジックを呼び出して、その#hide-divdiv を非表示にします。

*まあ、できますが、最初にそれらを定義してから渡す場合に限ります。このような:

var fn = function() {...};
$(document).ready(fn);

編集

質問者は ID やクラスを使用したくないため、別の解決策を次に示します。

<script>
    function hide() {
        $('div').hide();
    }
</script>
...
<button onclick="hide()">click for hide</button>
<div></div>

function hide()jQuery のドキュメント対応イディオム内に配置しないように注意してください。これを行うとhide()、スコープのために へのアクセスが拒否されます。

于 2012-07-07T05:32:03.147 に答える
0

Your code currently does nothing more than set the click handler when you click on the button.

If you want to continue to use the onclick handler on the button element, then change your hide function to simply $('div').hide() (without the $(fn).click part). If you'd rather use the click function to set the handler, then remove the onclick attribute from the button element, and in the function at the top change $(fn).click to $('#button').click, after giving your button an id of button.

于 2012-07-07T05:19:12.627 に答える
0

コンパクトな jQueryready()関数を他のものと混同しているので、$(document).ready()代わりに読み取り可能な構文を使用します。

$(document).ready(function() {
    $('.hide').on('click', function(){
        $(this).next('div').hide()
    })
})

HTML を少し変更します。

<button class="hide">click for hide</button>

関数を要素にバインドする代わりに、イベント ハンドラーを のクラスを持つ要素にバインドしhideます。それらがクリックされると、最も近い<div>要素を検索して非表示にします。

于 2012-07-07T05:27:36.877 に答える