如何多次触发定义为var的jQuery操作?
我需要多次使用一组不同的操作。正因为如此,我正在寻找一个“短码”来在不同的地方调用它们如何多次触发定义为var的jQuery操作?,jquery,Jquery,我需要多次使用一组不同的操作。正因为如此,我正在寻找一个“短码”来在不同的地方调用它们 var sth_happens = function(){ $("#red").animate(/* something */); $("#green").css({/* something */}); $("#yellow").css({/* something */}); .... and so on } $("#example").mouseenter(function
var sth_happens = function(){
$("#red").animate(/* something */);
$("#green").css({/* something */});
$("#yellow").css({/* something */});
.... and so on
}
$("#example").mouseenter(function(){
// I want to insert the above code here */
});
$("#example2").mouseeenter(function(){
// And here as well
});
我知道我可以像下面那样使用var sth\u ochines=function(){}
,这不是我想要做的:
var sth_happens = function(){/* Something happens */}
$("sth").click(example_name);
要解释代码应该如何工作:以下内容
$("#example").mouseenter(function(){
// I want to insert the above code here */
sth_happens();
});
$("#example2").mouseenter(function(){
// I want to insert the above code here */
sth_happens();
});
会变成
$("#example").mouseenter(function(){
$("#red").animate(/* something */);
$("#green").css({/* something */});
$("#yellow").css({/* something */});
.... and so on
});
$("#example2").mouseenter(function(){
$("#red").animate(/* something */);
$("#green").css({/* something */});
$("#yellow").css({/* something */});
.... and so on
});
我希望你能理解这个问题。如果没有,请随意询问 问题是因为
this
函数中的this
的范围与jQuery处理程序中的范围不同。您需要通过引用将函数提供给处理程序:
$("#red").mouseenter(this_happens);
或者,如果要保留匿名函数,则需要提供this
作为参数,或者使用call()
更改函数的范围:
$(此)
未定义它们的名称 嘿@Rory非常感谢你的回答,但我想你误解了我。“this”只是一个例子,我不是指查询词“this”。你可以用你想要的任何名字来代替它。我已经更新了我的问题,希望这样更容易理解!好的,那么你能解释一下你想要实现什么,因为目前还不清楚。以上就是你的小提琴例子的问题。也许我的问题太短了,因为我想让它尽可能简单。我已经更新了我的问题,希望这次更容易理解!嘿@void非常感谢你的回答,但我想你误解了我。“this”只是一个例子,我不是指查询词“this”。你可以用你想要的任何名字来代替它。我已经更新了我的问题,希望这样更容易理解!好的@MarianRick,你看到我在回答中附上的小提琴了。这是一组正在执行的操作。我已经阅读并理解了你的建议,但它不是我想要的(或者我无法根据自己的需要采纳)。我已经更新了我的问题,这样就更容易理解了。你想通过调用sth\u ockes()
插入这3行或更多的代码吗?@void是的!它就像一个专业的占位符,或者在less(如css框架)或php中定义一个变量,您可以在任何地方插入它!这就是我的代码所做的。我正在调用this_ockes()
,动画工作正常。您希望在我的代码中进行哪些修改?@void我真的很抱歉,我在自己的示例中遇到了问题。当然,你的答案绝对正确。在问这个问题之前,我先从你的代码开始,然后问了一个缺少的()
。正因为如此,它对我不起作用。您已经实现了$this
,将我的代码附加到目标元素上,这比我需要的更多。谢谢你的耐心!
$("#red").mouseenter(function(){
this_happens.call(this);
});
$(document).ready(function(){
var this_happens = function(ele){
ele.animate({"margin-left": "50px", "width": "100px"});
ele.css({"background-color":"green"});
}
$("#red").mouseenter(function(){
this_happens($(this));
});
});