为什么从数据列表中选择一个项目时,值末尾的 space 消失了?

Why does a space at the end of a value disappear when selecting an item from a datalist?

我 运行 遇到了一个奇怪的问题,即在使用数据列表时,值末尾的 space 消失了。这让我想知道为什么。 (我正在使用 google chrome)

我可以确保末尾的 space 将包含在 通过将最终结果分配给值属性,而不是在 <option></option> 标签之间。 JSFiddle 有效。

  1. 为什么 input (#datalist-input) 中的值去掉 space at 从数据列表中选择值时结束?
  2. 我应该在 <option></option> 标签之间使用 space 吗?如果是这样,为什么。如果不是,为什么不,为什么 <option> 标签只有在这种情况下才自动关闭?

JSFiddle link,删除 space: JSFiddle

html

<h3>The disappearing of a space at the end of a line</h3>
<input id="input" type="text" value="Space at the end " disabled="true">
<datalist id="datalist"></datalist>
<input id="datalist-input" list="datalist">
<h6>(select the only option in the datalist and click somewhere to trigger the script)</h6>

javascript/jQuery

let originalInput = $("#input").val();
$("#datalist").append(`<option>${originalInput}</option>`);
$("#datalist-input").change(function () {
    let datalistText = $("#datalist-input").val();
    if(datalistText !== originalInput) {
        alert(`The original value: "${originalInput}" is not equal to: "${datalistText}"`);
    } else {
        alert(`The original value: "${originalInput}" is equal to: "${datalistText}"`);
    }
}); // end change

只要您在选项文本中有前导或尾随空格,并且没有值属性,就会发生这种情况。

选项的文本用作值,空格被删除。

此行为在 HTML specification

中指定

The value attribute provides a value for element.
The value of an option element is the value of the value content attribute, if there is one, or, if there is not, the value of the element's text IDL attribute.

请注意,如果未设置值,它只是表示该值与 "text IDL" 相同,但对于选项,"text IDL" 指定如下

option . text
Same as textContent, except that spaces are collapsed.

它特别指出,如果元素上尚未设置此类属性,则在获取用于设置值属性的 "text IDL" 时会折叠空格,因此这是预期的行为。

下面的示例显示了将文本用作值与专门添加值属性之间的区别:

var t1 = $('#test1 option').get(0),
    t2 = $('#test2 option').get(0);
    
console.log( t1.value, t1.value.length );             // length === 10
console.log( t1.textContent, t1.textContent.length ); // length === 12

console.log( t2.value, t2.value.length );             // length === 22
console.log( t2.textContent, t2.textContent.length ); // length === 22

/*
    The option where the text is converted to a value property has a difference in length, the whitespace is trimmed.
    
    The option whith a value attribute, where the text isn't used for the value property, keeps the whitespace, and the length is the same
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test1">
  <option> has spaces </option>
</select>

<select id="test2">
  <option value=" has spaces and value "> has spaces and value </option>
</select>

这种情况下的解决方案是添加一个值

$("#datalist").append(`<option value="${originalInput}">`);