我想使用jquery隐藏按钮,而不是使用内联函数。
我有HTML:
<button id="mybutton" value="click me">click me</button>
和JS:
$("#mybutton").on("click", hideelement);
hideelement = function() {
$(this).hide();
}
点击时按钮不会隐藏。我做错了什么?
答案 0 :(得分:3)
如果您看到this question的已接受答案,您就会知道问题是什么
问题在于定义类似
的函数var funcName = function(){...}
所以在这种情况下你必须在定义后调用这个函数。否则它将无法使用。
像bellow
一样定义你的功能function hideelement() {
$(this).hide();
}
或者改变这样的顺序
hideelement = function() {
$(this).hide();
}
$("#mybutton").on("click", hideelement);
答案 1 :(得分:3)
添加更详细的已经正常工作的解决方案。
首先,确保您的代码位于body
的底部或document ready内部,类似于下面的内容,以确保代码在您的代码中位于DOM中执行:
$(document).ready(function(){
... your code here...
});
当代码执行时, $("#mybutton")
将不会在DOM中,并且不会绑定任何事件。
如果这不是问题并且事件已绑定,您可能会发现编写代码的方式会导致错误:Uncaught ReferenceError: hideelement is not defined
$("#mybutton").on("click", hideelement);
hideelement = function(){
$(this).hide();
}
以上代码实际上由JavaScript解释器解释如下:
var hideelement; // declaration was hoisted to the top of the scope
$("#mybutton").on("click", hideelement); // at this point hideelement is still 'undefined'
hideelement = function(){ // assignment of the value stays within the lexical scope
$(this).hide();
}
JavaScript会将声明提升到当前作用域的顶部,但会将作业保留在定义它的词法范围内。
但是,如果您将声明更改为:
$("#mybutton").on("click", hideelement);
function hideelement(){
$(this).hide();
}
现在JavaScript解释上面的代码如下:
function hideelement(){
$(this).hide();
}
$("#mybutton").on("click", hideelement); // hideelements is defined
由于hideelements
不再是一个赋值,而只是一个声明,整个函数将被提升,因此在事件绑定使用它时定义。
当然,在the other answer中已经建议的解决方案在使用它之前以词汇方式定义你的作业也是有效的。 I,E:
hideelement = function() {
$(this).hide();
}
$("#mybutton").on("click", hideelement);
为了简单起见,我故意没有进入全球化 范围和使用
var
的差异。
答案 2 :(得分:0)
$( "#mybutton" ).click(function() {
$( this ).hide();
});
答案 3 :(得分:-1)
试试这个$("#mybutton").click(function(){ $(this).hide() })
;
答案 4 :(得分:-1)
我在屏幕上看得太辛苦了。在反转函数定义并设置点击行为后,它起作用了。
hideelement = function() {
$(this).hide();
}
$("#mybutton").on("click", hideelement);