为具有相同类的元素分配唯一ID

时间:2012-12-18 15:58:13

标签: jquery

我正在创建一个网站,其中有两个不同的按钮。

通过使用jQuery,我想隐藏并显示两个元素。这两个元素都是文本。例如,点击buttonAtextA应显示,如果textB可见,则应隐藏。同样,点击buttonBtextB应显示,如果textA可见,则应隐藏。最初,文本都应该被隐藏,但是应该加载到他们的位置上。

两种文本在布局上都有相同的定位。我已经定义了一个类(.content是它的名字),它维护了文本的所有样式。现在我面临的问题是我在课堂上有两个div,但是我无法给文本两个不同的ID。

.content {
  visibility:hidden;
  border-style: none;
  display: block;
  position: fixed;
  text-align: centre;
  z-index: 1;
  margin-top: 40%;
  margin-left: 25%;
  margin-right: 25%;
  background-color: transparent;
  font-size:2.5em;
}

问题在于如何为两个文本分配一些独特的ID

<div class="content">TextA goes here<br></div>
<div class="content">TextB goes here<br></div>

所以当我使用jquery

$("#ButtonA").click(function(){
  $("#TextA").show();$("#TextB").hide();
});

$("#ButtonB").click(function(){
  $("#TextB").show();$("#TextA").hide();
});

虽然这可能是一个蹩脚的问题,但我无法弄明白,所以不得不问。

4 个答案:

答案 0 :(得分:8)

您不必添加id,只需使用jQuery -

即可
$("#ButtonA").click(function(){
    $('.content').eq(0).show();
    $('.content').eq(1).hide();
});

$("#ButtonB").click(function(){
    $('.content').eq(1).show();
    $('.content').eq(0).hide();    
});

答案 1 :(得分:0)

$("#ButtonA").click(function(){
    $('.content').eq(0).show();
    $('.content').eq(1).hide();
});

$("#ButtonB").click(function(){
    $('.content').eq(1).show();
    $('.content').eq(0).hide();    
});​

- 还改变了 -

.content {
    border-style: none;
    display: block;
    position: fixed;
    text-align: centre;
    z-index: 1;
    margin-top: 40%;
    margin-left: 25%;
    margin-right: 25%;
    background-color: transparent;
    font-size:2.5em;
    /* visibility: hidden; CHANGE THIS TO */
    display: none;
}​​

jsFiddle:http://jsfiddle.net/gEs66/1/

答案 2 :(得分:-1)

我不确定我完全理解这个问题,但我会采取这样的方法:

http://jsfiddle.net/HdhKQ/

HTML

<div class="row">
    <div class="content">TextA goes here</div>
    <div class="button">TextA Button</div>
</div>

<div class="row">
    <div class="content" style="display:none">TextB goes here</div>
    <div class="button">TextB Button</div>
</div>

CSS

.button { cursor:pointer; }

.content {
border-style: none;
display: block;
position: fixed;
text-align: centre;
z-index: 1;
margin-top: 40%;
margin-left: 25%;
margin-right: 25%;
background-color: transparent;
font-size:2.5em;
}​

JS $( “按钮”)。单击(函数(){

// Hide all content element
$(".content").hide();

// Show the content for the related button
$(this).parent().children('.content').show();

});

答案 3 :(得分:-3)

你能解释为什么你不能为元素使用不同的id吗?

<div class="content" id="TextA">TextA goes here<br></div>
<div class="content" id="TextB">TextB goes here<br></div>
相关问题