且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JQuery动态添加HTML的***方式是什么?

更新时间:2023-02-17 16:49:16

 < p>您可以将标签贴在表单元素的周围,这意味着您不必非常详细。 ;标签>< input type =radioid =dynamicRadioname =radio/> 
我的标签
< / label>
< br />

您可以像这样创建它:



function使用提供的参数创建一个新的单选按钮
var newRadio = $('< input />')。attr({
type:radio,id:id,name:id
});

//使用提供的参数创建一个新的单选按钮
var newLabel = $('< label />').append(newRadio).append(labelText);

//追加新的单选按钮并贴上
$('#dynamicRadioButtons')。append(newLabel).append('< br />');
}

我使用提供的id作为名称和id,否则所有的收音机都会有一个收音机的名字。您可能还需要重命名 OnClick ,因为在 onclick 事件处理程序中内置了内容,可能会导致混淆。 p>

以下是一个 JS小提琴


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?

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