使用任何变量

时间:2015-04-24 08:52:15

标签: javascript jquery html

我对javascript很陌生并且在使这个场景工作方面遇到了一些麻烦:我已经生成了元素#someotheridx,其中第一个x为1,每个添加元素都增长,因此#someotherid1 #someotherid2 #someotherid3等等。

我想用输入字段#someidx替换它。我可以通过使用下面的代码(称为onclick of a button)让它适用于任何元素,但我需要制作100个(用2s替换1s等等),这样如果用户创建了100个元素仍然有效。

如何创建一个函数以使其适用于所有元素?使用while或if?

function aaa1()
{
    var input = $('<input>', { val: $("#someid1").text(), class:"someclass",
                              type: "text" });
    $("#someotherid1").replaceWith(input);
    input.select();  
}

function aaa2()
{
    var input = $('<input>', { val: $("#someid2").text(), class:"someclass",
                              type: "text" });
    $("#someotherid2").replaceWith(input);
    input.select();  
}

1 个答案:

答案 0 :(得分:3)

只需一个功能即可使您的方案正常运行。

使用元素的索引/编号调用以下函数,它将为您完成魔法:)

function CommonFunction(index)
{
    var input = $('<input>', { val: $("#someid"+index).text(), class:"someclass",
                              type: "text" });
    $("#someotherid"+index).replaceWith(input);
   input.select();  
}