要将标签与收音机链接,而不是使用 JS 变量来维护,您可以生成一个唯一的 ID,如 GUID,并直接使用它。
删除块时,不需要ID,因为你有块内的关闭HTMLElement,你可以使用parent()函数和remove()函数来完成这项工作。
这是一个例子:
/**
* Generate a guid part
*/
function GuidPart()
{
return Math.floor(Math.random() * 0x10000).toString(16);
}
/**
* Generate a new GUID
*/
function getGuid()
{
return (GuidPart() + GuidPart() + "-" +
GuidPart() + "-" +
GuidPart() + "-" +
GuidPart() + "-" +
GuidPart() + GuidPart() + GuidPart());
}
/**
* Build a new block with radio, label and close span
*/
function buildNewRadio(labelText)
{
// Retrieve a new guid
var guid = getGuid();
// Create a span container with the radio and label inside
// linked together by the guid
var container = $(document.createElement("span")).append(
$(document.createElement("input")).attr('id', guid),
$(document.createElement("label")).attr('for', guid).val(labelText))
.addClass("container");
// Finally append the close span (use to remove the entiere block)
container.append(
$(document.createElement("span").addClass("close")
.click(function(mouseEvent) {
// Retrieve the span container and remove it
$(this).parent().remove();
}));
return container;
}
您可以调用 buildNewRadio 函数并将结果 HTMLElement 附加到您的 DOM 容器