【问题标题】:hide button with jquery [closed]用jquery隐藏按钮[关闭]
【发布时间】:2014-08-28 21:12:26
【问题描述】:

我想使用 jquery 隐藏点击按钮,而不是使用内联函数。

我有 HTML:

<button id="mybutton" value="click me">click me</button>

和 JS:

$("#mybutton").on("click", hideelement);

hideelement = function() {
    $(this).hide();
}

按钮不会在点击时隐藏。我做错了什么?

【问题讨论】:

  • Hiding button using jquery 的可能重复项
  • 不要重新发明轮子:$("#mybutton").on("click", function () { $(this).hide(); });
  • $("#mybutton").click(function() { $(this).hide(); });
  • 如果您查看浏览器控制台,我很确定那里有错误。
  • @MelanciaUK:匿名函数很难进行单元测试。命名函数不仅是一种很好的实践,而且还可以帮助您编写可测试的代码并支持将 DOM 操作与业务逻辑分离。此外,this 在这种情况下使用命名函数完美保留。

标签: javascript jquery


【解决方案1】:

如果您看到this question 的已接受答案,您就会知道问题出在哪里

问题是当你定义一个函数时

var funcName = function(){...}

所以在这种情况下你必须在定义后调用这个函数。否则将无法使用。

如下定义你的函数

function hideelement() {
    $(this).hide();
}

DEMO

或者像这样改变顺序

hideelement = function() {
    $(this).hide();
}

$("#mybutton").on("click", hideelement); 

DEMO

【讨论】:

【解决方案2】:

为已经工作的解决方案添加更多细节。


文档准备就绪


首先,确保您的代码位于body 的底部或document ready 内部,类似于以下内容,以确保在您的代码执行时该元素位于DOM 中。:

$(document).ready(function(){
   ... your code here...
});

$("#mybutton") 否则在代码执行时将不在 DOM 中,并且不会绑定任何事件。


变量吊装


如果这不是问题并且绑定了事件,您可能会发现您的代码编写方式会导致错误:Uncaught ReferenceError: hideelement is not defined

原因是variable hoisting

$("#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 不再是一个赋值,而只是一个声明,完整的函数将被提升,因此在事件绑定使用它时定义。


DEMO


当然,the other answer 中已经建议的解决方案是在使用它之前用词法定义你的赋值也将起作用。我,即:

hideelement = function() {
    $(this).hide();
}

$("#mybutton").on("click", hideelement); 

为了简单起见,我故意没有进入全局 范围和使用var的区别。

【讨论】:

    【解决方案3】:
    $( "#mybutton" ).click(function() {
        $( this ).hide();
    });
    

    http://jsfiddle.net/17n2faLo/

    【讨论】:

    • 虽然这行得通,但它并不能解释为什么 OPs 代码不能。
    【解决方案4】:

    试试这个$("#mybutton").click(function(){ $(this).hide() });

    【讨论】:

      【解决方案5】:

      我一直盯着屏幕看太用力了。在反转函数定义并设置点击行为后,它起作用了。

      hideelement = function() {
          $(this).hide();
      }
      
      $("#mybutton").on("click", hideelement); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-12
        • 1970-01-01
        • 1970-01-01
        • 2012-09-29
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        相关资源
        最近更新 更多