1

我正在尝试创建一个在按下时更改其值的按钮。

$("button").click( function() {
    valor = this.html();
    retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
    this.html(retorno);
});

我收到这条消息:

未捕获的类型错误:对象 # 没有方法 'html'

我很感激任何帮助。

4

7 回答 7

5

this是一个 HTMLElementNode 对象,而不是一个 jQuery 对象。

valor = jQuery(this).html();
于 2013-03-06T16:22:53.840 回答
2

this指的是 HTMLElementNode (窗口)对象,它不是一个 jquery 对象,因为 html 是一个 jquery 方法,所以它不起作用。

因此,要使其成为 jquery 对象,您需要将其包裹$起来:

 $("button").click( function() {
     valor = $(this).html();
     retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
     $(this).html(retorno);
 });
于 2013-03-06T16:23:53.610 回答
1

试试这个

valor = $(this).html();
于 2013-03-06T16:22:47.387 回答
1

用这个...

$("button").on('click', function() {
    valor = $(this).html();
    retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
    $(this).html(retorno);
});

看这个例子jsFiddle

于 2013-03-06T16:23:26.067 回答
1

this将引用 HTMLElementNode,因此您valor = this.innerHTML可以避免 jQuery 调用。

于 2013-03-06T16:24:07.047 回答
1
$("button").click( function() {
     valor = $(this).html();
     retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
     $(this).html(retorno);
 });
于 2013-03-06T16:25:14.140 回答
1

用这个 :

valor = jQuery(this).html();
于 2013-03-06T16:25:56.863 回答