【问题标题】:Change complex id value in Jquery Clone在 Jquery Clone 中更改复杂的 id 值
【发布时间】:2018-08-10 08:41:18
【问题描述】:

这是我的输入框

<input class="form-control" id="StudentInstitutes_0__Name" name="StudentInstitutes[0].Name" value="" type="text">

我使用clone() 来包装上述输入字段的 div。这很好用。

但是如何通过单击按钮来更改上面为“0”的 id 和名称索引。

例如:如果我第一次单击按钮,输入字段将是:

<input class="form-control" id="StudentInstitutes_1__Name" name="StudentInstitutes[1].Name" value="" type="text">

这是我的按钮

<div class="form-group">
    <div class="col-sm-6">
        <input type="button" name="ShowMoreInstitution" id="ShowMore" value="Add More Institution" onclick="javascript:  showMoreInstitution();" />
    </div>                                       
</div>

这是我的 JS

$("#showMore").click(function () {
    $('#showInstitute').clone().insertAfter("#showInstitute");
});

请注意,我使用的是 Asp.net Mvc Razor 视图,不想使用局部视图进行操作。

【问题讨论】:

  • 建议你参考this answer(创建一个模板并克隆它(id 属性对你来说毫无意义,所以最好删除它们 - 它的 name 属性很重要)
  • PS:除非您在页面上将 VBScript 作为第一个脚本,否则 onclick 处理程序中不需要javascript:
  • onclick 是做什么的 - 请删除它。同时单击&lt;&gt; 并创建一个minimal reproducible example,因为您的代码根本不起作用——showInstitute 在哪里?如果您保存克隆并在插入之前使用正则表达式更改名称/ID,它应该很简单
  • 解决了这个问题。谢谢@StephenMuecke

标签: javascript jquery asp.net-mvc


【解决方案1】:

据我所知,您想动态更改 id,因此您必须首先声明全局变量“value”并为其分配初始值 0。

$("#showMore").click(function () {
    value++;
    $('#showInstitute').removeAttr('id').attr('id', 'StudentInstitutes_" + value + "__Name');
});

此代码可能会对您有所帮助。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
相关资源
最近更新 更多