jQuery:html()在事件中不可用?

时间:2012-10-17 19:33:25

标签: javascript jquery

新手问题:

我有一个包含单个p元素的网页。我以为我可以访问事件中的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');
        });
    }
    );

6 个答案:

答案 0 :(得分:7)

处理函数中的

this是你的DOM元素..它没有.html函数..用$包装它以使它成为一个jQuery对象并执行{{1 }}

.html

完整代码:

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

答案 1 :(得分:5)

在您的上下文中使用this时,它是DOM元素。您可以使用本机方法,例如innerHTMLhtml是一个jQuery方法,需要您使用$(this).html()


<强>参考文献:

答案 2 :(得分: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.foo是DOM元素,在您的情况下为this

答案 3 :(得分:0)

修改后的代码:这不是jQuery对象。

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

答案 4 :(得分:0)

this是DOM元素,它不是jquery对象。所以使用$(this)

  $(this).html('this now works');

答案 5 :(得分:0)

试试这个(nned jQuery对象):

$( this ).html()