3

初心者の質問:

単一のp要素を持つWebページがあります。イベント内のp.html()にアクセスできると思いましたが、アクセスできません。イベント内の要素にjQuery要素としてアクセスする方法はありますか?

<script src="Scripts/jquery-1.8.2.js"></script>      
    $(function () {
        $("p").first().bind('click',null, function (event) {
            this.innerHTML = "this works";
            this.html('this does not');
        });
    }
    );
4

6 に答える 6

7

thisハンドラー内の関数はDOM要素です..関数はありません..それ.htmlをラップし$てjQueryオブジェクトにし、.html

$(this).html('this does work now');

完全なコード:

$(function () {
    $("p").first().bind('click',null, function (event) {
       this.innerHTML = "this works";
       $(this).html('this does work now');
    });
});
于 2012-10-17T19:34:07.203 に答える
5

コンテキストで使用thisする場合、それはDOM要素です。のようなネイティブメソッドを使用できますinnerHTMLhtmlはjQueryメソッドであり、を使用する必要があります$(this).html()


参照:

于 2012-10-17T19:34:36.017 に答える
1

を使用しているようthisに、それはDOMオブジェクトであり、「html」はjQueryオブジェクトのメソッドです。

jQuery objectを使用する前に、に変換する必要がありますjQuery api。変換するには、単純に $( DOM Object) 構造を使用します。

これで動作します -

$(function () {
    $("p").first().bind('click',null, function (event) {
        this.innerHTML = "this works";
        $(this).html('this works !!!)');
    });
}
);

jQuery APIによると-

$()— 指定されたセレクターに一致する要素を DOM で検索し、これらの要素を参照する新しい jQuery オブジェクトを作成します。

$('div.foo');

これがあなたの場合のdiv.fooDOM要素です。this

于 2012-10-17T19:38:20.583 に答える
0

変更されたコード:これはjQueryオブジェクトではありません。

    $(function () {
        $("p").first().bind('click',null, function (event) {
            this.innerHTML = "this works";
            $(this).html('this will work now');
        });
    }
    );
于 2012-10-17T19:34:20.840 に答える
0

thisDOM要素であり、jqueryオブジェクトではありません。$(this)

  $(this).html('this now works');
于 2012-10-17T19:34:52.170 に答える
0

これを試してください(nned jQueryオブジェクト):

$( this ).html()
于 2012-10-17T19:34:58.043 に答える