【问题标题】:Assign Jquery tokeninput for a dynamically created table row为动态创建的表行分配 Jquery tokeninput
【发布时间】:2015-04-19 07:32:25
【问题描述】:

已编辑

表格模板

<table id="Newdiagnosis" style="display:none">
<tr>
 <td><input class="diag" style="width:200px" type="text" name="provider_diagnosis_dtls[#].diagnosis_code" value /></td>
<td><input style="width:500px" type="text" name="provider_diagnosis_dtls[#].diagnosis_desc" value /></td>
<td>
<input type="text" name="provider_diagnosis_dtls[#].diagnosis_level)" readonly value />
<input type="hidden" name="diagnosis.Index" value="%" />
</td>
</tr>
 </table>

用于动态添加行的 Jquery

    $(document).ready(function () {
     $("#N").click(function () {
     var index = (new Date()).getTime();
     var clone = $('#Newdiagnosis').clone();
     clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
    clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
     $("#diagnosis").append(clone.html());
     });
 });

我需要为每个动态创建的文本框附加 Jquery tokeniput。有可能吗?

我在 Jquery 中尝试了以下代码

$("#N").click(function () {
    var index = (new Date()).getTime();
    var clone = $('#Newdiagnosis').clone();
    clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
    clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
    clone.find(".diag").tokenInput("@Url.Action("SearchDiagnosis", "Preapproval")", {
         theme: 'facebook',
         preventDuplicates: true,
         searchingText: 'Searching...',
         tokenLimit: 1
    });
    $("#diagnosis").append(clone.html());
});

这不是从 url 中给出的操作中搜索数据,但同样适用于非动态文本框

【问题讨论】:

  • 您需要将插件附加到新元素。添加id 属性的目的是什么?这篇文章将如何回复(您有重复的名称元素)?
  • 嗨,斯蒂芬,感谢您的回复。我不会有重复的名称元素,因为在元素的末尾分配了一个唯一的 ID。发回我需要调查一下。任何其他可以实现这一点的简单方法。我是 MVC 新手
  • 确实有重复的名称元素!这不可能正确回发。 id 属性无关紧要,您应该使用 new { id = "" } 因此删除 id 属性以避免无效的 html。建议你看看herehere的答案,了解如何动态生成集合项
  • 可以为动态创建的 texbox 附加 jquery inputtoken 吗?
  • 当然,只要给元素一个类名,然后在$("#N").click(function () - clone.find('.theClassName').tokenInput(....);

标签: jquery asp.net-mvc jquery-tokeninput


【解决方案1】:

在元素添加到 DOM 后,您需要将插件附加到元素上

var diagnosis = $("#diagnosis"); // cache it
$("#N").click(function () {
  var index = (new Date()).getTime();
  var clone = $('#Newdiagnosis').clone();
  clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
  clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
  diagnosis .append(clone.html());
  // Attach the plugin to the new element
  diagnosis.find('.diag').last().tokenInput('@Url.Action("SearchDiagnosis", "Preapproval")', {
    theme: 'facebook',
    preventDuplicates: true,
    searchingText: 'Searching...',
    tokenLimit: 1
  });
});

旁注:从您的 cmets 中,您指出某些元素具有 onchange=".."。您应该从标记中删除删除行为并使用事件委托来处理动态添加的元素

$("#diagnosis").on('change', '.diag', function() {
  // do something
});

【讨论】:

    猜你喜欢
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多