1

Hey I have the below javascript code with accompanying HTML. I am trying to get each button when clicked to change the text color to blue and then when the next button is clicked it changes text of the previously clicked button back to green. basically only the most recently clicked button has blue text. I have tried this code but with this it changes all button text to blue on the first button click. Any help is appreciated. Javascript, HTML, and CSS below.

function swapIphoneImage( tmpIPhoneImage ) {
    var el = document.getElementById('my-link');
    var el1 = document.getElementById('my-link1');
    var el2 = document.getElementById('my-link2');
    var el3 = document.getElementById('my-link3');
    var el4 = document.getElementById('my-link4');

    var iphoneImage = document.getElementById('iphoneImage');
    iphoneImage.src = tmpIPhoneImage;
    el.className = 'clicked-class';
    el1.className = 'clicked-class1';
    el2.className = 'clicked-class2';
    el3.className = 'clicked-class3';
    el4.className = 'clicked-class4';

}

html

<ul class="features">
    <li><a id="my-link"  href="javascript:swapIphoneImage('wscalendarws.png');" title="">HaPPPs Calendar</a></li>
    <li><a id="my-link1"  href="javascript:swapIphoneImage('wsweekendws.png');" title="">Weekend Events</a></li>
    <li><a id="my-link2"  href="javascript:swapIphoneImage('wsfollowingws.png');" title="">Places & People</a></li>
    <li><a id="my-link3"  href="javascript:swapIphoneImage('wstemplateviewws.png');" title="">Customize Events</a></li>
    <li><a id="my-link4"  href="javascript:swapIphoneImage('wscheckinws.png');" title="">Interaction</a></li>
</ul>

css

a#my-link.clicked-class {
    color: #71a1ff !important;
}
a#my-link1.clicked-class1 {
    color: #71a1ff !important;
}
a#my-link2.clicked-class2 {
    color: #71a1ff !important;
}
a#my-link3.clicked-class3 {
    color: #71a1ff !important;
}
a#my-link4.clicked-class4 {
    color: #71a1ff !important;
}

Where am I failing?

4

3 回答 3

2

尝试使用 JavaScript 更改类,然后您只需要一个类来确定单击了哪一个。

这是一个例子:

JS:

   $("UL.features LI A").click(function(){
      $("UL.features LI A").removeClass('clicked');
      $(this).addClass('clicked');
   });

CSS:

A.clicked {
    color:#71a1ff !important;
}

这是在jsfiddle:http: //jsfiddle.net/57PBm/

编辑:此解决方案使用 JQuery,如果您还没有,我肯定会建议使用

于 2013-02-13T02:07:16.580 回答
1

将 JS 代码重写为:

function swapIphoneImage( elThis, tmpIPhoneImage ) {
    var el = document.getElementByClassName('clicked-class');

    var iphoneImage = document.getElementById('iphoneImage');
    iphoneImage.src = tmpIPhoneImage;

    el.className = '';
    elThis.className = 'clicked-class';
}

和每个按钮:

<li><a id="my-link" href="javascript:swapIphoneImage(this, 'wscalendarws.png');" title="">HaPPPs Calendar</a></li>

您不需要为同一事物设置 5 个 CSS 类。

于 2013-02-13T02:11:12.553 回答
0

您正在将每个元素更改为单击的类。只需将一个数字传递给函数,该函数确定将哪个按钮着色为蓝色,然后通过 JS 将其中一个着色为蓝色,将其他所有着色为绿色。

于 2013-02-13T02:01:59.450 回答