如何选择以字符串开头但没有't在jQuery中以不同的字符串结尾

How to select for something that begins with a string but doesn't end with a different string in jQuery?

本文关键字:字符串 jQuery 结尾 选择 何选择 开头      更新时间:2023-09-26

我是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();                
});