gpt4 book ai didi

javascript - 带参数的 jQuery 函数

转载 作者:行者123 更新时间:2023-11-30 18:11:43 24 4
gpt4 key购买 nike

我是 jQuery 的新手,我正在尝试实现一个非常简单的工具提示,以了解 jQuery 的工作原理。

在谷歌搜索后,这就是我所做的:

jQuery:

$(document).ready(function(){

$("#foo1").mouseover(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$('#div1').css({'top':y,'left':x}).show();
});

$("#foo1").mousemove(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$('#div1').css({'top':y,'left':x});
});

$("#foo1").mouseout(function(){
$('#div1').hide();
});

})

HTML:

<div style="width: 200px; border: 1px black solid; position: relative;">
Something here
</div>
<div id="container" style="width: 300px; border: 1px black solid; position: relative;">
<a id="foo1" href="javascript:void(0);">[hover me]</a>
<div id="div1" class="tt">Content goes here.</div>
<a id="foo2" href="javascript:void(0);">[hover me too!]</a>
<div id="div2" class="tt">I'm not working :(</div>
</div>

我使用 var x = e.pageX - $("#container").offset().left; 因为当 #div1 在一个带有 position: relative;

的 div

一切正常,但如果我添加其他链接怎么办?

我想传递 #foo1#div1(最终是 #container,但实际上我真的不需要它)作为参数,但事实是我完全不知道如何做到这一点。

我试着在这里搜索,我找到了这个:JQuery, Passing Parameters

所以我想也许我可以这样做:

function doStuff(param1, param2) {
$(param1).mouseover(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$(param2).css({'top':y,'left':x}).show();
});
//etc etc
}

但我不知道如何在 HTML 中调用此函数:在 javascript 中我会做类似 onmouseover="doStuff('foo1', 'div1')" 的操作,但我不知道真的不知道如何使用 jQuery :|

编辑:

这是生成 div 的代码:

foreach ($colors_array as $key => $value) {
echo "<div id='foo" . $key . "'>";
// something else
// according to some condition, I will decide whether to
// call or not the function doStuff for this div.
echo "</div>";
}

最佳答案

这是另一个解决方案,在具有 tt 类的旁边找到元素:

$(document).ready(function(){

$(".tooltipped").mouseover(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$(this).next('.tt').css({'top':y,'left':x}).show();
});

$(".tooltipped").mousemove(function(e){
var x = e.pageX - $("#container").offset().left;
var y = e.pageY - $("#container").offset().top;
$(this).next('.tt').css({'top':y,'left':x});
});

$(".tooltipped").mouseout(function(){
$(this).next('.tt').hide();
});

})

你的 html :

<div id="container" style="width: 300px; border: 1px black solid; position: relative;">
<a id="foo1" class="tooltipped" href="javascript:void(0);">[hover me]</a>
<div id="div1" class="tt">Content goes here.</div>
<a id="foo2" class="tooltipped" href="javascript:void(0);">[hover me too!]</a>
<div id="div2" class="tt">I'm not working :(</div>
</div>

关于javascript - 带参数的 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14424280/

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