我一直认为input
元素被禁止拥有DOM内容,如here(位于'允许内容')和here(位于'提示和注释'中)。在另一个输入内嵌套输入
现在我正在一个项目中使用javascript呈现和更改几种不同的输入元素类型(例如,简单的input
文本元素和select
)。在那个变化的过程中,一个隐藏的input
放置在这些元素中,保持当前选定的值。
因此很明显,它是通过jQuery可能将一个input
元素添加到另一个输入元件(和使用它之后):
function doIt() {
//clear children of parent input
$('#parentInput').children().remove();
//create new input and append it to the parent input
$('<input>').attr({
type: 'hidden',
id: 'testInput',
value: 'Test value inserted into nested test input'
}).appendTo($('#parentInput'));
//get value of new nested input and write it to output div
$('#output').html($('#testInput').val());
}
$('#doIt').on('click', doIt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="Test" id="parentInput">
<button id="doIt">Do it</button>
<div id="output"></div>
甚至div
:
function doIt() {
//clear children of parent input
$('#parentInput').children().remove();
//create new input and append it to the parent input
$('<div id="testDiv">Test value inserted into nested test div</div>').appendTo($('#parentInput'));
//get value of new nested input and write it to output div
$('#output').html($('#testDiv').html());
}
$('#doIt').on('click', doIt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="Test" id="parentInput">
<button id="doIt">Do it</button>
<div id="output"></div>
我现在的问题是:当input
元素不应该有DOM内容时,为什么通过jQuery(并因此通过纯javascript,因为jQuery只是一个包装)而导致possbile?
有几种类型的输入https://www.w3schools.com/html/html_form_input_types.asp,其中一些我们不放内容,其他的我们放内容。检查链接中的列表。 – MedAli
我不确定这是否与您的问题100%相关,但请查看[Shadow DOM](https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom)。 –
浏览器支持很多未在W3C/HTML规范中明确表示支持的行为。一般而言,您希望避开这些“功能”,因为它们在不同的浏览器中可能不会相同,或者更糟糕的是,浏览器补丁可能完全改变或破坏其行为。 – jbabey