【问题标题】:What's the best way to add HTML dynamically with JQuery?使用 JQuery 动态添加 HTML 的最佳方法是什么?
【发布时间】:2012-01-07 09:44:24
【问题描述】:

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

【问题讨论】:

  • 我在 jsfiddle 上一团糟,想出了这个解决方案,足以让我继续使用,但这是最好的方法吗? jsfiddle.net/uNNMr/881

标签: jquery html radio-button label


【解决方案1】:

您可以将标签包裹在表单元素周围,这意味着您不必那么冗长。

<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

【讨论】:

  • 谢谢,太好了!关于方法名称 OnClick 的好点 - 我只是心不在焉地输入它作为示例。
猜你喜欢
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
相关资源
最近更新 更多