这是我创建输入字段的原始代码:

$('#dynamicForm').append('<li id="pdport"></li>');
$('#pdport').append("<label for='sport'>Destination port</label>")
$('<input>').attr({type: 'text', id: 'dport', name: 'dport'}).appendTo('#pdport');
$('#pdport').append("<span>Enter the destination port here (0-65535)</span>");


而不是一遍又一遍地执行此代码,我试图为其创建一个函数

function createInputfield(mainID, childID, labelFor, labelText, spanText){
    $(mainID).append('<li id=childID></li>');
    $(childID).append("<label for=labelFor>labelText</label>")
    $('<input>').attr({type: 'text', id: labelFor, name: labelFor}).appendTo(childID);
    $(childID).append("<span>spanText</span>");
}


而不是使用

createInputfield("#dynamicForm", "#psport", "sport", "Source port", "Enter the source port here (0-65535)");


这样,我可以创建很多动态输入字段,而无需复制/粘贴很多相同的代码。

问题是这行不通,我总是会遇到语法错误,就像您不能附加在mainID和其他ID上一样。我尝试了很多不同的方法来完成此操作,例如使用引号,使用单引号而不使用..但是似乎没有任何效果。

最佳答案

您忘记对变量进行转义并将其连接到字符串

function createInputfield(mainID, childID, labelFor, labelText, spanText){
    $(mainID).append('<li id='+childID.replace('#','')+'></li>');
    $(childID).append("<label for="+labelFor+">"+labelText+"</label>")
    $('<input>').attr({
        type: 'text',
        id: labelFor,
        name: labelFor
    }).appendTo(childID);
    $(childID).append("<span>"+ spanText +"</span>");
}


这可能有效

10-04 22:55
查看更多