我正在尝试创建一个按钮,在按下按钮时会更改其值。
$("button").click( function() {
valor = this.html();
retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
this.html(retorno);
});
我收到了这条消息:
未捕获TypeError:对象#没有方法'html'
我感谢任何帮助。
答案 0 :(得分:5)
this
是一个HTMLElementNode对象,而不是jQuery对象。
valor = jQuery(this).html();
答案 1 :(得分:2)
this
是指HTMLElementNode(window)对象,不是jquery对象,而html是一个jquery方法,它不起作用。
所以要使它成为一个jquery对象,你需要将$
包裹起来:
$("button").click( function() {
valor = $(this).html();
retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
$(this).html(retorno);
});
答案 2 :(得分:1)
试试这个
valor = $(this).html();
答案 3 :(得分:1)
使用此...
$("button").on('click', function() {
valor = $(this).html();
retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
$(this).html(retorno);
});
请参阅此示例jsFiddle
答案 4 :(得分:1)
this
将引用HTMLElementNode,因此您可以执行valor = this.innerHTML
并避免jQuery调用。
答案 5 :(得分:1)
$("button").click( function() {
valor = $(this).html();
retorno = (valor == 'Exibir') ? 'Ocultar' : 'Exibir';
$(this).html(retorno);
});
答案 6 :(得分:1)
使用此:
valor = jQuery(this).html();