简体   繁体   中英

Javascript code on link click runs only once, I want to get it run everytime when link is clicked

I have designed a template, and i am giving options to users, to change style of div, they have 5 different options to choose from, each style is associated with each class name, so when ever a user clicks a link it will change the div style. So, I changed the class name of div with javascript code:

function changeClass(value){

        style = [ 'view view-first', 'view view-second', 'view view-third', 'view view-fourth', 'view view-fifth' ];
         var elements = document.getElementsByClassName("test");
         for(var i = elements.length - 1; i >= 0; i--)
        {

            // PERFORM STUFF ON THE ELEMENT
            elements[i].className = style[value];

            // elements[i] no longer exists past this point, in most browsers
        }   
        }

1st I collected class name of divs i want to change and stored it in an array,

2nd I created a new array with new class name.

3rd I ran a loop and assigned new class name to divs.

4th I incorporated onClick changeClass(0) changeClass(1) etc event on links and ran the function.

The following code is ok, when i click the link for the 1st time, when i click another link with onClick event, the style dosent change. In particular class name change is only happening when i click on any of the links for the 1st time in the page.

My objective is to change style of divs according to the associated link.

It only works the first time because you are searching for elements with the test class. Then you replace the class with the ones from the function. So there are no elements with test class after the first run, and subsequently nothing is found on the following runs.

Workaround ( is to keep the test class, but use it only for selecting and not for styling )

 var style = ['view view-first', 'view view-second', 'view view-third', 'view view-fourth', 'view view-fifth']; function changeClass(value) { var targetClass = "test", elements = document.getElementsByClassName( targetClass ); for (var i = elements.length - 1; i >= 0; i--) { // PERFORM STUFF ON THE ELEMENT elements[i].className = targetClass + ' ' + style[value]; // elements[i] no longer exists past this point, in most browsers } }
 .view-first{color:red;} .view-second{color:blue;} .view-third{color:green;} .view-fourth{color:yellow;} .view-fifth{color:orange;}
 <div class="test">Test #1</div> <p> irrelevant text </p> <div class="test">Test #2</div> <p> irrelevant text </p> <p> irrelevant text </p> <div class="test">Test #3</div> <div class="test">Test #4</div> <div class="test">Test #5</div> <p> irrelevant text </p> <p> irrelevant text </p> <p> irrelevant text </p> <div class="test">Test #6</div> <div class="test">Test #7</div> <button onclick="changeClass(0);">first (red)</button> <button onclick="changeClass(1);">second (blue)</button> <button onclick="changeClass(2);">third (green)</button> <button onclick="changeClass(3);">fourth (yellow)</button> <button onclick="changeClass(4);">fifth (orange)</button>


An alternative with jQuery

var style = ['view view-first', 'view view-second', 'view view-third', 'view view-fourth', 'view view-fifth'];

function changeClass(value) {
    $('.test').removeClass().addClass( style[value] ).addClass( 'test' );
}

You're obliterating all the classes on your queried elements when you execute elements[i].className = style[value]; so document.getElementsByClassName("test") won't match anything on subsequent invocations.

It's not exactly clear what your intentions are, but if you just want to add to your class list, replace elements[i].className = style[value]; with elements[i].className += style[value];

After the initial call to changeClass, there would no longer be any Classnames of "test".

 elements[i].className = style[value];

Is changing the className "test" to whatever index of style is specified in the function call.

It therefore cannot find the class name "test" after the initial call to do anything. You would have to refresh the page or call a different function to change the classnames back to "test".

You might want to declare IDs of "test1", "test2", "test3" and so forth.

Then you can call (if the elements are inputs):

var inputs = document.getElementsByTagName("input");

for (var i = 0; i < inputs.length; i++) {
  if(inputs[i].id.indexOf("test") >= 0)
    inputs[i].className = style[value]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM