HTML 选择永久显示值

HTML select permanent display value?

本文关键字:显示 选择 HTML      更新时间:2023-09-26

如何使下拉选择框始终显示相同的值,而不是所选值?

例:

<select value="Color">
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

我希望选择框在选择时始终显示"颜色"而不是"蓝色"或"红色"。

鉴于您能够接受JavaScript解决方案,如您的评论中所述,我可以为您提供以下解决方案,该解决方案应该可以根据您的需求进行扩展和定制。

不过,它可以简化,这可能对任何(潜在的)未来用户都有好处:

// simple function to uppercase the first letter of a given string,
// if it's a lower-case letter:
// of a given string:
function upperCaseFirst(str) {
    return str.replace(/^[a-z]/, function (firstLetter) {
        return firstLetter.toUpperCase();
    });
}
// as above, but from upper-case to lower-case:    
function lowerCaseFirst(str) {
    return str.replace(/^[A-Z]/, function (firstLetter) {
        return firstLetter.toLowerCase();
    });
}
function showOptionString(opts) {
    /* these are the defaults,
       replace: Boolean, true/false
                true - replaces the option-text with the
                       supplied prefix/suffix strings
                false - wraps the option-text with the
                        supplied prefix/suffix strings
       sentenceCaseOption: Boolean, true/false
                true - lower-cases both the first letter of
                       the option-text, and the first-letter
                       of the option's original text when
                       constructing the new text
                false - maintains both the option-text's case
                       and that of the supplied prefix-string
       separator: String,
                the string with which the option-text should be
                separated from the supplied prefix/suffix
       prefixString: String,
                the text which will precede the option-text (if
                settings.replace is set to false), or which will
                replace the option-text (by default)
       suffixString: String,
                the text which will follow the option-text (if
                settings.replace is set to false), or which will
                replace the option-text (by default)
    var settings = {
        'replace': true,
            'sentenceCaseOption': true,
            'separator': ' ',
            'prefixString': '',
            'suffixString': ''
    };
    // if the user has supplied options:
    if (opts) {
        // we iterate through the properties of the settings object and
        for (var prop in settings) {
            // if the property is of the object itself (not from
            // elsewhere in the prototype chain)
            if (settings.hasOwnProperty(prop)) {
                // overwrite the property of the settings object,
                // if that property is not undefined in the supplied
                // options object (otherwise we 'retain' the default):
                settings[prop] = opts[prop] !== undefined ? opts[prop] : settings[prop];
            }
        }
    }
    // having used Function.prototype.call when assigning the
    // the event-handler, 'this' is the <select> element:
    var select = this,
        // retrieving the <option> elements from the <select>
        options = select.options,
        // finding the selected <option>
        selected = options[select.selectedIndex],
        // we use String.prototype.trim() later to remove
        // leading/trailing white-space from the option-text;
        // here we create a regular expression to remove non white-
        // space portions of the supplied separator string.
        // removing leading white-space from the separator
        // ' : ' would become ': '
        leading = settings.separator.replace(/^'s+/, ''),
        // removing trailing white-space from the separator
        // ' : ' would become ' :'
        trailing = settings.separator.replace(/'s+$/, ''),
        // creating a single regular expression, using the 'new RegExp()'
        // constructor which will match the above strings when found
        // at the beginning (leading) or end (trailing) of the
        // option-text:
        trimReg = new RegExp('^' + leading + '|' + trailing + '$', 'g');
    // using forEach to iterate over the array-like NodeList of
    // <option> elements:
    Array.prototype.forEach.call(options, function (opt) {
        // opt is the current <option> of the NodeList over
        // which we're iterating.
        // creating a property on the Node, setting its 'oldValue' property
        // to be equal to its oldValue property or, if not yet set, to its
        // current text:
        opt.oldValue = opt.oldValue || opt.text;
        // setting the text back to its oldValue (this is to revert
        // previously-changed text back to its original form):
        opt.text = opt.oldValue;
    });
    // if settings.replace is true:
    if (settings.replace) {
        // we set the selected-option's text to a string created by
        // joining an Array of the prefixString and suffixString
        // together with the separator string:
        selected.text = [settings.prefixString, settings.suffixString].join(settings.separator);
    } else {
        // otherwise, if sentenceCaseOption is true:
        if (settings.sentenceCaseOption) {
            // do much the same, except we include the option-text's
            // lower-cased oldValue in the string we create:
            selected.text = [settings.prefixString, lowerCaseFirst(selected.oldValue), settings.suffixString].join(settings.separator);
        } else {
            // and, if we don't need/want to sentence-case the
            // option text we do exactly the same as above, but
            // without calling lowerCaseFirst() on the oldValue:
            selected.text = [settings.prefixString, selected.oldValue, settings.suffixString].join(settings.separator);
        }
    }
    // here we get the selected-option's text, trim the
    // leading/trailing white-space from it and replace any
    // remaining portions of the separator that might exist.
    // if settings.sentenceCaseOption is true,
    // we use upperCaseFirst() to upper-case the first-letter,
    // otherwise we do not:
    selected.text = settings.sentenceCaseOption ? upperCaseFirst(selected.text.trim().replace(trimReg, '')) : selected.text.trim().replace(trimReg, '');
}
// a reference to the first <select> element from the document:
var select = document.querySelector('select');
// adding a 'change' event-listener to the <select> element:
select.addEventListener('change', function () {
    // assigning the showOptionString() function as
    // the event-handler, together with Function.prototype.call
    // to pass the <select> element to the function, inside of
    // of which it will be the function's 'this':
    showOptionString.call(this, {
        // setting some of the user-supplied options:
        'prefixString': 'color',
            'suffixString': '',
            'separator': ' - '
    });
});

function upperCaseFirst(str) {
  return str.replace(/^[a-z]/, function(firstLetter) {
    return firstLetter.toUpperCase();
  });
}
function lowerCaseFirst(str) {
  return str.replace(/^[A-Z]/, function(firstLetter) {
    return firstLetter.toLowerCase();
  });
}
function showOptionString(opts) {
  var settings = {
    'replace': true,
    'sentenceCaseOption': true,
    'separator': ' ',
    'prefixString': '',
    'suffixString': ''
  };
  if (opts) {
    for (var prop in settings) {
      if (settings.hasOwnProperty(prop)) {
        settings[prop] = opts[prop] !== undefined ? opts[prop] : settings[prop];
      }
    }
  }
  var select = this,
    options = select.options,
    selected = options[select.selectedIndex],
    leading = settings.separator.replace(/^'s+/, ''),
    trailing = settings.separator.replace(/'s+$/, ''),
    trimReg = new RegExp('^' + leading + '|' + trailing + '$', 'g');
  Array.prototype.forEach.call(options, function(opt) {
    opt.oldValue = opt.oldValue || opt.text;
    opt.text = opt.oldValue;
  });
  if (settings.replace) {
    selected.text = [settings.prefixString, settings.suffixString].join(settings.separator);
  } else {
    if (settings.sentenceCaseOption) {
      selected.text = [settings.prefixString, lowerCaseFirst(selected.oldValue), settings.suffixString].join(settings.separator);
    } else {
      selected.text = [settings.prefixString, selected.oldValue, settings.suffixString].join(settings.separator);
    }
  }
  selected.text = settings.sentenceCaseOption ? upperCaseFirst(selected.text.trim().replace(trimReg, '')) : selected.text.trim().replace(trimReg, '');
}
var select = document.querySelector('select');
select.addEventListener('change', function() {
  showOptionString.call(this, {
    'prefixString': 'color',
    'suffixString': '',
    'separator': ' - ',
  });
});
<select value="Color">
  <option value="blue">Blue</option>
  <option value="red">Red</option>
</select>

请注意,虽然我已经尽我所能回答了这个问题以满足您的用例和声明的要求,但我反对完全替换<option>文本(这就是为什么我在提供的功能中将其作为用户可配置选项提供的原因),因为它看起来(对用户)好像没有进行任何更改导致他们必须至少重新打开一次<select>, 只是为了检查。

因此,我几乎肯定会将replace: false设置为函数的默认值:

function showOptionString(opts) {
  var settings = {
    'replace': false,
    'sentenceCaseOption': true,
    'separator': ' ',
    'prefixString': '',
    'suffixString': ''
  };
  /* ... rest of function ... */
}

function upperCaseFirst(str) {
  return str.replace(/^[a-z]/, function(firstLetter) {
    return firstLetter.toUpperCase();
  });
}
function lowerCaseFirst(str) {
  return str.replace(/^[A-Z]/, function(firstLetter) {
    return firstLetter.toLowerCase();
  });
}
function showOptionString(opts) {
  var settings = {
    'replace': false,
    'sentenceCaseOption': true,
    'separator': ' ',
    'prefixString': '',
    'suffixString': ''
  };
  if (opts) {
    for (var prop in settings) {
      if (settings.hasOwnProperty(prop)) {
        settings[prop] = opts[prop] !== undefined ? opts[prop] : settings[prop];
      }
    }
  }
  var select = this,
    options = select.options,
    selected = options[select.selectedIndex],
    leading = settings.separator.replace(/^'s+/, ''),
    trailing = settings.separator.replace(/'s+$/, ''),
    trimReg = new RegExp('^' + leading + '|' + trailing + '$', 'g');
  Array.prototype.forEach.call(options, function(opt) {
    opt.oldValue = opt.oldValue || opt.text;
    opt.text = opt.oldValue;
  });
  if (settings.replace) {
    selected.text = [settings.prefixString, settings.suffixString].join(settings.separator);
  } else {
    if (settings.sentenceCaseOption) {
      selected.text = [settings.prefixString, lowerCaseFirst(selected.oldValue), settings.suffixString].join(settings.separator);
    } else {
      selected.text = [settings.prefixString, selected.oldValue, settings.suffixString].join(settings.separator);
    }
  }
  selected.text = settings.sentenceCaseOption ? upperCaseFirst(selected.text.trim().replace(trimReg, '')) : selected.text.trim().replace(trimReg, '');
}
var select = document.querySelector('select');
select.addEventListener('change', function() {
  showOptionString.call(this, {
    'prefixString': 'color',
    'suffixString': '',
    'separator': ' - ',
    'replace': false,
  });
});
<select value="Color">
  <option value="blue">Blue</option>
  <option value="red">Red</option>
</select>

或者,相反,作为传入选项,作为 UI 功能:

select.addEventListener('change', function() {
  showOptionString.call(this, {
    'prefixString': 'color',
    'suffixString': '',
    'separator': ' - '
    'replace' : false,
  });
});

function upperCaseFirst(str) {
  return str.replace(/^[a-z]/, function(firstLetter) {
    return firstLetter.toUpperCase();
  });
}
function lowerCaseFirst(str) {
  return str.replace(/^[A-Z]/, function(firstLetter) {
    return firstLetter.toLowerCase();
  });
}
function showOptionString(opts) {
  var settings = {
    'replace': true,
    'sentenceCaseOption': true,
    'separator': ' ',
    'prefixString': '',
    'suffixString': ''
  };
  if (opts) {
    for (var prop in settings) {
      if (settings.hasOwnProperty(prop)) {
        settings[prop] = opts[prop] !== undefined ? opts[prop] : settings[prop];
      }
    }
  }
  var select = this,
    options = select.options,
    selected = options[select.selectedIndex],
    leading = settings.separator.replace(/^'s+/, ''),
    trailing = settings.separator.replace(/'s+$/, ''),
    trimReg = new RegExp('^' + leading + '|' + trailing + '$', 'g');
  Array.prototype.forEach.call(options, function(opt) {
    opt.oldValue = opt.oldValue || opt.text;
    opt.text = opt.oldValue;
  });
  if (settings.replace) {
    selected.text = [settings.prefixString, settings.suffixString].join(settings.separator);
  } else {
    if (settings.sentenceCaseOption) {
      selected.text = [settings.prefixString, lowerCaseFirst(selected.oldValue), settings.suffixString].join(settings.separator);
    } else {
      selected.text = [settings.prefixString, selected.oldValue, settings.suffixString].join(settings.separator);
    }
  }
  selected.text = settings.sentenceCaseOption ? upperCaseFirst(selected.text.trim().replace(trimReg, '')) : selected.text.trim().replace(trimReg, '');
}
var select = document.querySelector('select');
select.addEventListener('change', function() {
  showOptionString.call(this, {
    'prefixString': 'color',
    'suffixString': '',
    'separator': ' - ',
    'replace' : false,
  });
});
<select value="Color">
  <option value="blue">Blue</option>
  <option value="red">Red</option>
</select>

引用:

  • Array.protoype.forEach() .
  • Array.protoype.join() .
  • document.querySelector() .
  • EventTarget.addEventListener() .
  • for...in循环。
  • Function.prototype.call() .
  • HTMLOptionElement .
  • HTMLSelectElement .
  • JavaScript RegularExpressions。
  • Object.prototype.hasOwnProperty() .
  • RegExp()构造函数。
  • String.prototype.replace() .
  • String.prototype.toLowerCase() .
  • String.prototype.toUpperCase() .
  • String.prototype.trim() .

这是代码:

<select>
<option value="color" selected>Color</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

您可以将 selected 属性添加到第一个option现在将color 希望这有帮助。