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

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

本文介绍了使用JQuery动态添加HTML的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML:

<div id="dynamicRadioButtons">



</div>

使用jQuery,我想在上面的div上附加一个带有相应标签的单选按钮.我要附加的HTML示例如下:

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>

因此,可以说我有一个函数,当我单击某项并获取参数id(这是要创建的单选按钮的ID)和labelText(这是要创建的标签的文本)时,就会调用该函数,我希望能够做这样的事情:

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

有人可以帮我做我的待办事项吗?我正在按照此页面的示例 但是只是对jQuery不够了解以添加标签等.这是否是动态添加HTML元素的最佳方法?

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?

推荐答案

您可以将标签包裹在form元素周围,这意味着您不必太冗长.

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 />

您可以这样创建它:

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的事件处理程序,这可能会引起混乱.

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.

以下是示例 JS小提琴

这篇关于使用JQuery动态添加HTML的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 03:48