2017-08-04 37 views
0

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

+0

有幾種類型的輸入https://www.w3schools.com/html/html_form_input_types.asp,其中一些我們不放內容,其他的我們放內容。檢查鏈接中的列表。 – MedAli

+0

我不確定這是否與您的問題100%相關,但請查看[Shadow DOM](https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom)。 –

+6

瀏覽器支持很多未在W3C/HTML規範中明確表示支持的行爲。一般而言,您希望避開這些「功能」,因爲它們在不同的瀏覽器中可能不會相同,或者更糟糕的是,瀏覽器補丁可能完全改變或破壞其行爲。 – jbabey

回答

0

我一直認爲輸入元素被禁止擁有DOM內容,如此處所述(在'允許內容')和此處(在'提示和註釋'中)。

您混淆了HTML和DOM。 HTML只是文本。 DOM是瀏覽器根據該文本創建的內容。

以下是HTML。這是無效的,沒有瀏覽器會從它創建嵌套的節點:

<input type="text" value="Test" id="parentInput"> 
    <div id="testDiv">Test value inserted into nested test div</div> 
</input> 

瀏覽器創建將最有可能看起來像是從這個HTML附帶的DOM樹:

<input type="text" value="Test" id="parentInput"> 
<div id="testDiv">Test value inserted into nested test div</div> 

結束標記被忽略。當談到解析HTML時,瀏覽器是寬容的。

如果您直接操作DOM,那麼瀏覽器沒有理由阻止該操作。當呈現DOM的時候,瀏覽器知道如何呈現輸入。它並不在乎輸入節點是否有子節點。它簡單地被忽略。

0

某些瀏覽器可能(或不可能)支持W3C/HTML規範中未特別支持的行爲。通常,您希望避開這些「功能」,因爲它們在不同的瀏覽器中可能不會相同,或者更糟糕的是,瀏覽器補丁可能會因爲它們未被記錄而完全改變或破壞它們的行爲。

相關問題