简体   繁体   中英

Javascript onchange only with specific option class

I have a dropdown box, when onchange redirects to a url - works fine. However I only want it to trigger the onchange when the option has a class of ".level-0" - how do I do that?

<script type="text/javascript">
    <!--
    var dropdown = document.getElementById("cat");
    function onCatChange() {
        if ( dropdown.options[dropdown.selectedIndex].value != -1 ) {
            location.href = "<?php echo home_url();?>/?sfid=770&_sft_city-type="+dropdown.options[dropdown.selectedIndex].value;
        }
    }
    dropdown.onchange = onCatChange;
    -->
</script>

In modern browsers, you can use classList.contains(). If you need to support older browsers, you need look at the className string directly.

function onCatChange() {
    var option = dropdown.options[dropdown.selectedIndex];
    if (option.value != -1 && option.classList.contains("level-0")) {
        location.href = "<?php echo home_url();?>/?sfid=770&_sft_city-type="+option.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