HTML选择永久显示值?

时间:2015-01-18 20:30:21

标签: javascript html css

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

示例:

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

我希望选择框始终显示&#34; color&#34;而不是&#34;蓝色&#34;或&#34;红色&#34;当他们被选中。

2 个答案:

答案 0 :(得分:0)

鉴于您已经能够接受JavaScript解决方案,如your comment所述,我可以为您提供以下解决方案,该解决方案应该可以根据您的需求进行扩展和自定义。

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

// 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': ' - '
    });
});

&#13;
&#13;
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': ' - ',
  });
});
&#13;
<select value="Color">
  <option value="blue">Blue</option>
  <option value="red">Red</option>
</select>
&#13;
&#13;
&#13;

请注意,虽然我已尽最大努力满足您的用例和规定的要求,但我仍然反对完全替换<option>文本(这就是我提供的原因)它作为提供的函数中的用户可配置选项),因为它(对用户)看起来好像没有进行任何更改,导致他们必须至少重新打开<select>一次,只是为了检查。

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

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

&#13;
&#13;
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,
  });
});
&#13;
<select value="Color">
  <option value="blue">Blue</option>
  <option value="red">Red</option>
</select>
&#13;
&#13;
&#13;

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

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

&#13;
&#13;
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,
  });
});
&#13;
<select value="Color">
  <option value="blue">Blue</option>
  <option value="red">Red</option>
</select>
&#13;
&#13;
&#13;

参考文献:

答案 1 :(得分:-1)

以下是代码:

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

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