如何选择以字符串开头但没有't在jQuery中以不同的字符串结尾
How to select for something that begins with a string but doesn't end with a different string in jQuery?
我是jQuery的新手,正在探索它的语法。
我的页面有这样的元素:
<area id="SA" ... />
<area id="AF" ... />
<area id="EU" ... />
<area id="NA" ... />
我试图根据area
标签上的点击事件来显示和隐藏div
部分,这些标签有匹配的结束ID,编码如下:
<div id="div_SA" ... />
<div id="div_AF" ... />
<div id="div_EU" ... />
<div id="div_NA" ... />
因此,为了显示完全匹配,但隐藏所有id以"div_"开头但不匹配的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类并用类名来处理它们,但我仍然很好奇如何构建一个以这种方式工作的查询。)
让事情变得尽可能简单,因为你是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();
});
希望这能暂时帮到你。如果没有,请告诉我。
编辑:请参阅下面的文章中提到的语法修复
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();
DEMO
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();
这个怎么样:
$('area').click(function() {
var areaID = $(this).attr('id');
$('div[id^="div_"]').hide();
$('div[id^="div_' + areaID + '"]').show();
});
//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();
简短而简单的
// cache divs, no need to search them again
var divs=$('div[id^="div_"]');
$('area').click(function(){
divs.hide().eq( $(this).index() ).show();
});
相关文章:
- 字符串Jquery结构中的变量
- 在字符串 jquery 中添加空格
- 如何在字符串 jQuery 上调用函数
- 将 .val() 转换为字符串 jQuery
- 如何放置 PHP 字符串 jQuery 验证错误消息
- 查找字符串 jQuery/Javascript 的部分
- 从字符串 jQuery 中删除字符串
- 比较明显相等的字符串 JQuery
- 在字符串中使用 PHP 作为字符串.(JQuery)
- 比较两个字符串(jquery .text() 和文字字符串)
- 替换<a>如果它以字符串JQuery结尾
- 字符串jQuery剩余的空白数量
- 重新注册字符串jquery.Ui可拖动
- 字符串替换为另一个字符串jquery/javascript
- 如果子值与某个字符串JQuery匹配,则隐藏父元素
- 单击时从输入中删除字符串?jQuery
- 如何获取特定子字符串jquery之后的字符串
- 不能识别父-字符串JQuery中的子字符串
- 翻译KeyDown键码字符串(jQuery)
- 即使我没有引号来转义,它仍然说我有一个未闭字符串(Jquery)