gpt4 book ai didi

Javascript/jQuery 编码模式建议

转载 作者:行者123 更新时间:2023-11-30 08:51:04 25 4
gpt4 key购买 nike

我正在努力提高我对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com