使用JQuery动态添加HTML的最佳方法是什么?

时间:2011-11-27 17:01:41

标签: jquery html radio-button label

我有以下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元素的最佳方法吗?

1 个答案:

答案 0 :(得分: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作为名称和id,否则所有无线电将具有“radio”的名称。您可能还想重命名OnClick,因为名为onclick的事件处理程序中存在内置,这可能会导致混淆。

以下是JS Fiddle

的示例