使用 jQuery 选择多个对象
基本上我尝试让链接滑下 div。这相当简单,但是我需要多个链接向下滑动各自的 div。我知道我可以只命名链接和 div 唯一的类并以这种方式解决问题,但这自然也需要为每个链接 div 复制 jQuery 代码,而我有很多。因此我需要一个通用脚本。我的情况的简化版本如下:
HTML:
<div>
<a id=link1>toggle text 1</a>
<div class=link1>TEXT 1</div>
<a id=link2>toggle text 2</a>
<div class=link2>TEXT 2</div>
</div>
我尝试使用 jQuery 通用脚本来实现此目的:
$(document).ready(function() {
$('[id^=link]').bind('click', function() {
var $div = $(this).attr('id');
if($('[class=' + div + ']').is(':visible')) {
$('[class=' + div + ']').slideUp();
} else {
$('[class=' + div + ']').slideDown();
}
return false;
});
});
但正如人们所期望的,因为我在这里写它,所以它不起作用。我认为这与 ^= 有关,但我不知道如何改进它。
Basically I attempt to have a link slide down a div. This is fairly simple however I require multiple links sliding down their respective divs. I understand I can just name the links and divs unique classes and solve the problem that way, however this naturally also requires a duplication of the jQuery code for each link-div and i have a lot. I therefore need a general script. A simplified version of my situation is as follows:
HTML:
<div>
<a id=link1>toggle text 1</a>
<div class=link1>TEXT 1</div>
<a id=link2>toggle text 2</a>
<div class=link2>TEXT 2</div>
</div>
My attempt at a jQuery general script for this:
$(document).ready(function() {
$('[id^=link]').bind('click', function() {
var $div = $(this).attr('id');
if($('[class=' + div + ']').is(':visible')) {
$('[class=' + div + ']').slideUp();
} else {
$('[class=' + div + ']').slideDown();
}
return false;
});
});
But as one might expect since I'm writing here it does not work. I am thinking is has to do with the ^= but I can't figure out how to improve it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
那行不通?
Wouldn't that work?
我建议在所有链接上使用一个公共类,例如...
您可以选择多个...
替代方案,您可以选择所有 A 标签...
I would suggest having a common class on all your links, for example...
and you can select multiple with...
alternative, you could select all A tags....
两个问题:
您声明了一个变量
$div
但使用了div
要按类选择,请使用
.classname
而不是'[class=...]
优化:
选择您的 div 并重新使用变量
$div
以避免重新选择同一元素 3 次,
this
是 DOM 元素。要获取其 ID,只需使用this.id
,不需要这是代码:
演示
Two problems:
you were declaring a variable
$div
but usingdiv
to select by class, use
.classname
and not'[class=...]
Optimizations:
select your div and re-use the variable
$div
to avoid re-selecting 3 times the same elementin an event handler,
this
is the DOM element. To get its ID, just usethis.id
, not need for jqueryHere's the code:
DEMO
我意识到其他人正在提出替代方案,我鼓励您看看它们。为了回答您的具体问题,我相信它在于变量名称:
然后带有
div
的代码行,例如应该有
$div
代替。I realise that others are suggesting alternatives, and I would encorage you to look at them. To answer your specific problem I believe it lies with the variable names:
The lines of code with
div
in then, e.g.Should possibly have
$div
instead.您可以尝试这个更详细的示例...希望这有帮助:
You can try this more verbose example... hope this helps: