简体   繁体   中英

Javascript | Change src to data-attribute active

I am trying to change the selection of a image based on a data attribute of 'data-active'.

When the data-active is equal to true, then it will change the image to something that indicates that the platform has been selected and all of the others deselect showing only one.

The problem I currently have is that the image is being passed the current platform that is clicked so it is changing the deselected images to the current image clicked on disabled so the images become out of order.

You can see this here... https://miotks.co.uk/register (I have a self assigned certificate)

This is my current code that I have for it...

function checkState(obj, platform) {
var checkActive = document.querySelectorAll("[data-active='true']");
var alreadyActive = checkActive.length;

if (alreadyActive >= 2) {
    for (var i = 0; i < checkActive.length; i++) {

        // Reset the images to the default when all changed to false.
        checkActive[i].setAttribute('data-active', 'false');
        checkActive[i].setAttribute('src', '/images/' + platform + '-noselect.png' );

        obj.setAttribute('data-active', 'true');
        obj.setAttribute('src', '/images/' + platform + '-select.png');
    }
} else {

}}

It judges the length of how many elements are selected and have 'true' once this exceeds or is equal to 2, then they all get reset and should change to the current one.

This is how I am calling the function on the click event...

checkState(this, 'steam');

It looks like you can just change the -select to -noselect in each image's url:

function checkState(obj, platform) {
    var checkActive = document.querySelectorAll("[data-active='true']");
    var alreadyActive = checkActive.length;

    if (alreadyActive) {
        for (var i = 0; i < checkActive.length; i++) {
            // Reset the images to the default when all changed to false.
            checkActive[i].setAttribute('data-active', 'false');
            checkActive[i].src = checkActive[i].src.replace('-select', '-noselect');
        }
    }

    obj.setAttribute('data-active', 'true');
    obj.src = obj.src.replace('-noselect', '-select');
}

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