jQuery – 使用类的最后一位找到多个关联的类?

我有以下HTML代码:

Contact Details EditHide
Contact Details EditHide

类“hide1”和“hide2”的跨度设置为在页面加载时显示:none。

在此代码中,使用jQuery,我尝试执行以下操作:

  • 如果单击edit1,则此跨度将变为隐藏,并且具有类“hide1”的关联跨度变为可见。
  • 对于代码中的所有其他跨距,这应该是相同的,例如edit2和hide2。 此外,如果我想进一步添加编辑和隐藏类,该函数也应该能够处理这个,例如edit3和hide3等等。

到目前为止,我已经能够找到单击的编辑范围并将其隐藏。 我正在努力获得相关的“隐藏”课程。 有人可以帮我这么做吗? 到目前为止,这是我的jQuery函数:

  var spans = $("#myIntForm").find("span[class^='edit'],span[class^='hide']"); spans.click(function() { var $this = $(this); spans.filter("span[class^='hide']").hide(); if($this.attr('class').substr(0,4)=='edit') { var visible = $this.filter("span[class^='"+$this.attr('class').substr(0,4)+"']"); visible.hide(); //find the class 'hide' with same ending number as class 'edit' and display it. var invisible; } }); 

我以前做过类似的事情,我更容易以某种方式划分类名 – 即下划线,并使用ID来帮助选择如下:

 Edit 1 Hide 1 

然后你可以找到这样的相关类:

 $(function(){ $('.hide').hide(); $('.edit').click(function(){ //each time an edit class is clicked, show its associated hide div var aNum = $(this).attr('id'); //get the number at the end of the ID of this particular edit div aNum=(aNum.substring(aNum.indexOf('_')+1, aNum.length)); //select and show the associated hide_1 div $('#hide_'+aNum).show(); //hide $(this) $(this).hide(); }); }); 

我没有测试过这个,但你明白了。 另一点是,我认为你不需要将$(this)分配给var,我在你的代码中看不到任何可以保证的东西。

希望这可以帮助

编辑:忘记在点击时隐藏编辑div,代码更新

第二次编辑:Woops,错过了一个关键的支架,还需要一个+1子串:)现在工作正常 – 在这里得到一个例子: http : //jsfiddle.net/rYMtq/

现在有点不相干,你得到了一个答案但是一个未闭合的支架足以让我在晚上保持清醒:D

我已经继续并改变了一些你的jQuery代码。 这是一个有实例的jsfiddle 。 希望能帮助到你。

 var $spans =$("#myIntForm").find("span[class^='edit'],span[class^='hide']"); $spans.click(function() { var $this = $(this), $hideSpan = $this.siblings('span[class^="hide"]'), $editSpan = $this.siblings('span[class^="edit"]'); $this.toggle(); $hideSpan.toggle(); $editSpan.toggle(); });