【问题标题】:Apply CSS/ javascript after jquery replaceWith在 jquery replaceWith 之后应用 CSS/javascript
【发布时间】:2013-05-17 20:50:36
【问题描述】:

我在 ajax 请求后替换了 html 表中的一行。 成功请求后,我会收到一个部分 html 片段,我将其替换为当前行。

$("#id").replaceWith(response)

现在我添加了一个复选框输入字段,并使用这个 css 和 js 库 Bootstrap Switch 拉皮条。

所以在我替换行后,我只看到一个普通的输入复选框。而不是漂亮的切换。 如果我刷新页面,则会呈现切换。

任何人都可以帮助我并指出这个问题的问题吗? 我尝试在行和父级上使用 trigger('create')。

这是我用于更新表格的代码,就像我提到的那样,它只是进行替换。

processRecord = (barCode, random_id) ->
  postParams = { barCode: barCode, ran_id: random_id }

  $.ajax
    url: '/scans'
    type: 'post'
    data: postParams

    success: (response, textStatus, xhr) ->
      $("#" + random_id).replaceWith(response)
      $("#scans").trigger('create')

我一直在研究引导开关代码。 init 方法将导致在渲染后将额外的 html 添加到输入复选框。当我进行替换时,这不会发生。看这里:https://github.com/nostalgiaz/bootstrap-switch/blob/master/static/js/bootstrapSwitch.js#L14

谢谢

【问题讨论】:

  • 如果您有 JavaScript 事件附加到元素,您可能需要将它们委托给父元素,或者在完成 replaceWith 后重新运行它们。如果没有您的更多代码,我们将无法为您提供进一步的帮助。
  • 你可以试试 $("#table_id_or_class").trigger('create');
  • 不幸的是触发动作不起作用

标签: jquery html ajax refresh partial-page-refresh


【解决方案1】:

更换元素后需要重新初始化switch插件。

success: (response, textStatus, xhr) ->
  $("#" + random_id).replaceWith(response)

      // assuming #scans is the parent of inputs
      var sc = $("#scans").

  if (!sc.hasClass('has-switch')) { // this is to prevent stacking
     sc['bootstrapSwitch'](); // if has-switch is not found, use switch plugin
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2014-10-13
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多