从数据列表中选择项目时,为什么值末尾的空格会消失?
作者:互联网
我遇到一个奇怪的问题,在使用数据列表时,值末尾的空格消失了.这让我想知道为什么. (我正在使用谷歌浏览器)
我可以确保最后的空格将包含在
通过将其分配给value属性,而不是在< option>之间和< / option>标签. JSFiddle有效.
>为什么输入(#datalist-input)中的值会删除空格
从数据列表中选择值的结尾?
>我应该在< option>之间使用空格吗?和< / option>标签吗?如果是这样,该怎么办.如果不是,为什么< option>不是?仅在这种情况下才自动关闭标签?
JSFiddle链接,它删除了空间: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
解决方法:
每当选项的文本中有前导或尾随空白并且没有value属性时,就会发生这种情况.
该选项的文本用作值,空白被剪裁掉.
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’stext
IDL
attribute.
请注意,如果未设置任何值,它只是说该值与“文本IDL”相同,但是对于选项,“文本IDL”的指定如下
option . text
Same as textContent, except that spaces are collapsed.
具体来说,如果在元素上尚未设置值属性的“文本IDL”已被设置,则空格将被折叠,因此这是预期的行为.
这是一个示例,显示了将文本用作值与专门添加value属性之间的区别:
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}">`);
标签:html-select,html,javascript,jquery 来源: https://codeday.me/bug/20191111/2017735.html