Javascript/jQuery 编码模式建议

标签 javascript jquery

我正在努力提高我对 javascript/jQuery 函数模式的理解。我一直在玩这个简单的演示,试图让一个有启发性的模块模式发挥作用。

谁能帮我理解为什么这不起作用?我知道实际上您只需使用 CSS 即可解决问题,并且还有其他简单的方法可以解决它 - 我感兴趣的是为什么我尝试的解决方案不起作用。

HTML

<body>

<p>Here is a test input element</p>
<form>
    <label>Some label</label>
        <input type="text">
        <button>Click me</button>
</form>

</body>

</html>

jQuery:

$(document).ready(function(){

var roll = (function(){     
      function rollEnter(){
      $("button", this).css("text-decoration", "underline");
      }     
      function rollExit(){
      $("button", this).css("text-decoration", "none");
      }     
    return{
    underlined: rollEnter,
    standard: rollExit
    };
})();


//When I try and call the functions, it doesn't work
    $("button").on('mouseenter', roll.underlined());
    $("button").on('mouseleave', roll.standard());

});

关于哪里出了问题/如何让这种模式起作用有什么建议吗?

最佳答案

这里有两个问题:

  1. 您在事件处理程序中调用回调函数,而不是让事件处理程序调用它们。

    // roll.underlined is invoked immediately
    $("button").on('mouseenter', roll.underlined());
    // roll.underlined is invoked when button emits the 'mousenter' event
    $("button").on('mouseenter', roll.underlined);
    
  2. 您在每个回调中将不需要的上下文传递给您的 jQuery 选择器

    // nonworking: no need for "this"
    function rollEnter(){
      $("button", this).css("color", "red");
    } 
    // working 
    function rollEnter(){
      $(this).css("color", "red"); // $(this) is element event was triggered on
    } 
    

jsbin

关于Javascript/jQuery 编码模式建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17815674/

相关文章:

c# - 我的oauth2回调页面可以是同一个html页面吗?我如何获得 token ?

javascript - 在 Nodejs 中解析嵌套的 JSON

javascript - 我如何在JS中将数字(例如: 2. 12)四舍五入到最接近的十分之一(2.1)

javascript - 将 div 向下滑动到页面中间

JavaScript 使用 FormData 和 jQuery 的 ajax 上传文件在 iOS 上没有选择文件时返回错误 500

jQuery:IE6 中的窗口控件问题

jquery - 如何在使用 jquery .click 函数单击第二次后删除 CSS 属性?

javascript - 纯 Javascript 中的 jQuery .load template.html

javascript - 在鼠标悬停时显示弹出窗口并在鼠标悬停时关闭它

d :h:m:s 的 JavaScript 倒计时