-3

私が知っている方法:

HTML:

<input type="button" id="msg" onclick="foo(this);" />

JS:

function foo(elementObj) { elementObj.toggle(); }

関数の引数として渡さずにelementObj内部への参照を取得する方法はありますか?foo()

私がやりたい方法:

HTML:

<input type="button" id="msg" onclick="foo();" />

JS:

function foo() { elementObj = <any way I can get ref to html element here?>; elementObj.toggle(); }

PS

次のように関数を呼び出します。$("#msg").click(function(elementObj ) {elementObj.toggle();}

私が必要とするものではありません。

4

3 に答える 3

2

関数の引数として渡さずにelementObj内部への参照を取得する方法はありますか?foo()

はい、適切で目立たない jQuery イベント ハンドラーを使用するだけ.onです。

$('#msg').click(function() {
    //`this` references the clicked DOM element #msg
});

または、関数を他の場所で使用する必要がある場合foo..

function foo(eventObject) { 
    //`this` reference the #msg element
}
$('#msg').click(foo);

OP編集によると:

function foo() {
   elementObj = <any way I can get ref to html element here?>;
   elementObj.toggle();
}

ええ、IDセレクターを使用する$('#msg')$(this)、クリックした要素を参照したい場合。

function foo() {
   var elementObj = $(this);
   elementObj.toggle();
   //or more directly $(this).toggle()
}
$('#msg').click(foo);
于 2013-01-30T00:00:36.413 に答える
0

あなたの例は私にはうまく見えます。

関数にパラメーターを渡すからといって、それを使用する必要があるわけではありません。

関数内で必要な要素への参照を取得できます。

<input type="button" onclick="foo(this);" />

<script>

    function foo(thisIsNotUsed) {
        var anotherElement = document.getElementById("someId");
        // create a jQuery object before invoking toggle
        jQuery(anotherElement).toggle();
    }

</script>

ノート:

ハンドラーを HTML に登録することは恐ろしい慣行であるというのがコンセンサス意見であると確信しています。

于 2013-01-30T00:03:39.760 に答える
-1

jqueryを使用して参照を取得できます。次のことを試してください。

<input type="button" onclick="foo(this);" />

//javascript
$(document).ready(function(){
   $('input').on('click', function(){
      var theElement = $(this);
   });
});
于 2013-01-30T00:01:37.560 に答える