我一直認爲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