我是jQuery的新手,稍微探索一下它的语法。
我的页面包含以下元素:
<area id="SA" ... />
<area id="AF" ... />
<area id="EU" ... />
<area id="NA" ... />
我正在尝试根据div
代码中的点击事件显示和隐藏area
部分,这些代码具有匹配的结尾ID,编码如下:
<div id="div_SA" ... />
<div id="div_AF" ... />
<div id="div_EU" ... />
<div id="div_NA" ... />
因此,要显示完全匹配,但要隐藏所有div
部分,这些部分的ID以“div_”开头但不匹配,而不会隐藏页面上的所有其他div
,我试过这个:
var q = 'div[id="div_' + event.target.id + '"]';
var r = 'div[id^="div_"],div:not[id$=' + event.target.id + '"]';
$(q).show();
$(r).hide();
$(r).hide();
无效。我究竟做错了什么? (我知道我可以分配CSS类并使用类名来获取它们,但我仍然对如何构建一个以这种方式工作的查询感到好奇。)
答案 0 :(得分:2)
让事情变得简单和简单,因为你是jQuery的新手,你应该养成使用on()
的习惯。不是click()
,那是过时的,只是简单地引用了on方法。
$('area').on('click', function() {
var id = "#div_" + $(this).attr('id'), // comma allows you to make multiple variables
divs = $('div').hide() // puts all the divs in a variable and automatically hides them all
// filter through all the divs, and selects the one with the id,
// of the area that was clicked, and shows it
divs.filter(id).show();
});
希望这对你现在有所帮助。如果没有,请告诉我。
答案 1 :(得分:1)
not
css伪选择器使用括号而不是括号。此外,在最后一个括号之前,您还有一个不匹配的引号。
var r = 'div[id^="div_"],div:not(#' + event.target.id + ')';
此外,您可以通过将代码更改为:
来简化代码var q = '#' + event.target.id;
var r = 'div[id^="div_"]:not(#' + event.target.id + ')';
$(q).show();
$(r).hide();
答案 2 :(得分:1)
修改:请参阅下文,了解帖子中提到的语法修复
var q = '#div_' + this.id;
var r = 'div[id^="div_"]:not("#div_' + this.id + '")';
$(r).hide();
$(q).show();
请查看下面的替代解决方案,
为了评估q,我只想使用
var q = $('#div_' + this.id);
对于r,
var r = $('div[id^="div_"]').not(q);
r.hide();
q.show();
答案 3 :(得分:1)
这个怎么样:
$('area').click(function() {
var areaID = $(this).attr('id');
$('div[id^="div_"]').hide();
$('div[id^="div_' + areaID + '"]').show();
});
答案 4 :(得分:0)
//start by selecing all of the DIV elements that have an ID attribute that starts with "div_",
//and hide all of them,
//then filter that list down to only the element(s) that have an ID that ends with the id of the `event.target` element
//and show that/those element(s)
$('div[id^="div_"]').hide().filter('#div_' + event.target.id).show();
答案 5 :(得分:0)
短而简单
// cache divs, no need to search them again
var divs=$('div[id^="div_"]');
$('area').click(function(){
divs.hide().eq( $(this).index() ).show();
});