What's the best way to add HTML dynamically with JQuery?

柔情痞子 提交于 2019-12-11 23:22:45

问题


I have the following HTML:

<div id="dynamicRadioButtons">



</div>

Using jQuery I'd like to append a radio button with corresponding label to the above div. An example of the HTML I'd like to append is as follows:

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

So, lets say I have a function that's called when I click something and takes the parameters id (which is the id of the radio button to be created) and labelText (which is the text of the label to be created), I want to be able to do something like this:

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 */);    
}

Can someone help me with my TODO bits please? I was following an example as per this page but just don't know enough about jQuery to add the label etc. Also is this the best way to dynamically add HTML elements?


回答1:


You can wrap your label around the form element, which means you don't have to be quite so verbose.

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

And you can create it like this:

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 />');
}

I have used the supplied id for the name and id, otherwise all radios would have a name of "radio". You might also want to rename OnClick as there are build in event handlers called onclick and it might cause confusion.

Here is an example JS Fiddle



来源:https://stackoverflow.com/questions/8287266/whats-the-best-way-to-add-html-dynamically-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!