Declare a JavaScript function which can hide the label of the calling HTML element

前端 未结 5 1106
猫巷女王i
猫巷女王i 2021-01-29 07:01

HTML


5条回答
  •  清酒与你
    2021-01-29 07:37

    This hides the label of the corresponding input.

    function focus() {
        var labels = document.getElementsByTagName('label');
        for(var i = 0; i < labels.length; i ++) {
            var attr = labels[i].getAttribute('for'); //or labels[i].htmlFor
            if(attr === this.id) {
                labels[i].style.visibility = 'hidden';
                //or labels[i].style.display = 'none';
            }
        }
    
    }
    
    document.getElementById('ABC').addEventListener('focus', focus);
    document.getElementById('DEF').addEventListener('focus', focus);
    

    JSFiddle

    A jQuery solution:

    $('input').on('focus', function() {
        $('label[for=' + this.id + ']').hide();  
    });
    

提交回复
热议问题