2011-11-27 90 views
0

我有以下HTML:使用JQuery動態添加HTML的最佳方式是什麼?

<div id="dynamicRadioButtons"> 



</div> 

使用jQuery我想追加一個單選按鈕與相應的標籤上面的DIV。我想追加HTML的一個例子如下:

<input type="radio" id="dynamicRadio" name="radio" /><label for="dynamicRadio">My Label</label> <br> 

因此,可以說我有一個當我點擊的東西,就是所謂的和需要的參數ID(這是單選按鈕的ID功能要創建)和LabelText的(這是標籤的文本,以創建),我希望能夠做這樣的事情:

function OnClick(id, labelText){ 

    // create a new radio button using supplied parameters 
    var $newRadioBtn = $('<input />').attr({type="radio", id=id, name="radio"}); 

    // create a new radio button using supplied parameters 
    // TODO - set the value of the label to parameter: labelText 
    var $newLabel = $('<label />').attr({for=id}); 

    // TODO - append the new radio button and label to the div and then append <br>... 
    $('#dynamicRadioButtons').append(/* The elements I want to append */);  
} 

有人可以幫助我與我的TODO位嗎?我正在關注一個示例as per this page,但只是不太瞭解jQuery來添加標籤等。此外,這是動態添加HTML元素的最佳方式嗎?

+0

我有一個爛攤子有關的jsfiddle以及與此解決方案,它是足以讓我保持與工作,但這個是最好的辦法想出了? http://jsfiddle.net/uNNMr/881/ –

回答

4

您可以將標籤包裹在表單元素的周圍,這意味着您不必非常詳細。

<label><input type="radio" id="dynamicRadio" name="radio" /> 
    My Label 
</label> 
<br /> 

你可以這樣創建:

function OnClick(id, labelText) { 

    // create a new radio button using supplied parameters 
    var newRadio = $('<input />').attr({ 
     type: "radio", id: id, name: id 
    }); 

    // create a new radio button using supplied parameters 
    var newLabel = $('<label />').append(newRadio).append(labelText); 

    // append the new radio button and label 
    $('#dynamicRadioButtons').append(newLabel).append('<br />'); 
} 

我已經使用的名稱和標識的提供的ID,否則,所有的無線電將有「無線電」的名稱。您可能還想重命名爲OnClick,因爲在事件處理程序中內置了名爲onclick的內部版本,可能會導致混淆。

下面是一個例子JS Fiddle

+0

謝謝,這很完美!關於方法名稱OnClick的好處 - 我只是不經意地將其作爲例子輸入。 –

相關問題